+ 3
what is return? how to understand easily?
please someone help me to understand return statement easily.
7 Answers
+ 7
The return value of a function is what it sends back. When reaching return, the execution of your function ends and the function sends back the indicated value.
Example:
function square(n){
return n*n;
}
document.write(square(3)); //writes 9
+ 4
Your suggested change:
function square(n){
document.write(n*n);
}
square(3);
The difference with the previous one is that the function returns nothing, so you can't use it to get the result of the calculation and do other stuff with it (you can't do var a = square(3) for example). Also, it will always print the result, which is not necessarily what you wanted to do with the function.
+ 1
if we write document.write(n*n); in the functions and calls it, it is also give us same output, what is difference between those two
+ 1
@Zen that's perfect
0
thank you friend I understood little bit I will try this code
0
The function is the main advantage of programming language in which programming codes can be grouped together. There are mainly 3 types of functions
1. A function without parameter and no return value .
eg. : funtion printHi( ) {
document.write("Hi");
}
printHi();
2. A function with parameter and no return value
eg. : function printHi(x) {
document.write("Hi "+x+", Weolcome !);
}
3. A function with parameter and return value :
By return value it means that, a function will execute some instructions and after that the result will be return to the part of the code who call that function .
eg: var x = 3;
var y = 5;
var z = sum(x,y);
function sum( a,b) {
return a+b ; // return the calulated value
}
A return is simply an output of the function.
0
assume you have a function which will compute square root of the given no. As you know that the no. of lines required will be greater that 20 lines of code. Now assume that you have to calculate the sqrt in diffrent parts of the coding. If you have created a function for finding sqrt, then you dont need to write code again!
i.e the biggest advantage of function is the "Code Resusability"
here all you need is to call sqrt(value) whenever you need to calculate the same.