Question about return command


#1

Hello.

I was just wondering about the "return" command within a function.
For example,you can say:
var example = function(num) {
return num * 2;
}

However, what I was wondering what the difference between saying "return num *2" and "num * 2" would be.
Also, what would happen if you put
return num * 2;
num+3;

or something along those lines?

Thanks!


#2

Consider the following diagram:

caller -------------->------------ caller
             /              \
             -<-- callee -<--

The path illustrated describes the flow of data, starting with the function call argument:

var foo = function (bar) {
    return bar;
};
console.log(foo("FooBar")); // FooBar

The function foo is the callee. Data enters the function through the formal parameter, and is used in the function. New data is sent back to the caller by way of the return statement. The above is simple identity function that returns what it is given, but most times, like your example, we do something with the parameter and return the result.

The return statement is not implicit in JavaScript. If we want a value returned, we have to declare it explicitly.

var timesTwo = function (number) {
    return number * 2;
};
console.log(timesTwo(21));  // 42

#3

what would happen if you put

return num * 2;
num+3;

?

Any code that follows return is unreachable since flow is transfered out of the function back to the caller.