开发者

JavaScript return value [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldw开发者_如何学编程ide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜