JavaScript Functions

Returning a Value

While updating global variables is one way to pass information back to the code that called the function, this is not an ideal way of doing so. A much better alternative is to write the function so that values that are used by the function are passed to it as parameters and the function returns whatever value that it needs to without using or updating any global variables.

By limiting the way in which information is passed to and from functions we can make it easier to reuse the same function from multiple places in our code.

JavaScript provides for passing one value back to the code that called it after everything in the function that needs to run has finished running.

JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return. That value can be a constant value, a variable, or even a calculation where the result of the calculation will be returned.

return 3;
return xyz;
return true;
return x / y + 27;

You can include multiple return statements into your function each of which returns a different value. In addition to returning the specified value the return statement also acts as an instruction to exit from the function at that point. Any code that follows the return statement will not be run.

function num(x, y) {
if (x !== y) {return false;}
if (x < 5) {return 5;}
return x;

The above function shows how you control which return statement is run by using if statements.

The value that is returned from a call to a function is the value of that function call. For example with that function we can set a variable to the value that is returned using the following code (which would set result to 5).

var result = num(3,3);

The difference between functions and other variables is that the function has to be run in order to determine its value. When you need to access that value in multiple places in your code, it is more efficient to run the function once and assign the value returned to a variable. That variable is used in the rest of the calculations.

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow