return Statements

By: Dusty Arlia
Published on Monday, April 22, 2013, 06:09 PM
Last Updated on Tuesday, July 14, 2015 at 6:00 PM
Total Updates: 6

return statements send a value from the function, back to the function call. This is called "returning a value". return statements are only found in the body of functions; anywhere else would be a syntax error. Here is the basic syntax of a return statement:

return [expression];

After the return keyword comes a single expression. The expression can be a variable, a literal value, or some other kind of single expression. This expression gets evaluated and its resulting value is sent back to the function call. If you need to return multiple values, use a single array.

Here is an example:

return x;

When this statement is done executing, control of your JavaScript program returns back to your function call. Any statements that come after the return statement in the function body will not execute.

Here is some examples of some incorrect return statements:

//you can only have a single value returned
//resulting from a single expression

return variable_one, variable_two;

//or

//you can't have a line break in between
//the return keyword and your expression

return
[your_expression];

In the examples above, you see that you can't include multiple expressions or line breaks after your return keyword.

You are also able to leave a return statement empty, with no expression, if you do not want to return a value. Here is an example:

return;

What this does is exit the function and returns control of your program back to where you called the function. But instead of returning a value, the function returns a value of undefined.

You also have the option of not including a return statement in your function. With no return statement, your function executes each statement sequentially until it reaches the end of the function body. At that point it returns the value undefined back to the function call. The function call is also referred to as the invocation expression. In this example, the invocation expression is said to evaluate to undefined.

Comments:

Ad: