JavaScript return value [closed]
I'm learning JavaScript as my first language and I'm getting the idea here as far as functions go but I don't understand what the point of the return value at the end is.
What is it used for?
To put it simply, a value is returned so you can use it elsewhere in your program. Consider the following (pretty pointless) function:
function addNumbers(x, y) {
return x + y;
}
When you call that function, you supply 2 arguments x
and y
. The function body adds those together and returns the result. You probably want to be able to use the result, so when you call the function you can assign the result to a variable:
var added = addNumbers(5, 10); //addNumbers returns 5 + 10
alert(added); //Alerts 15
And now that you have a variable added
with the result of calling the function, you can use that anywhere else in the containing scope of that variable. That means you don't have to call addNumbers(5, 10)
over and over again every time you want to use the result of it.
The return value is passed back to whatever called the function.
function myFunction() { return 1; }
alert(myfunction()); // alerts 1
var foo = myFunction(); // assigns 1 to foo
The return stamenet finish the method and returns the value for the caller.
A function performs a task of some sort. Sometimes you need to see the result of a task, and sometimes you don't. Run this code for example:
function multiply(a, b)
{
return a * b;
}
alert( multiply(2, 2) );
The return value of multiply() (in this case "4") will become the argument of the alert() function. This code will therefore show an alert box with the number 4 in it.
精彩评论