The add function adds its two parameters, and then returns it. This becomes the value returned by the call to the function at add(4, 5)
, and so the number 9 is logged to the console.
Functions can return any type of value, such as numbers, strings or booleans. Since JavaScript is dynamically typed, functions can even return different types in different circumstances, such as a string in an 'if' statement and a number in an 'else' statement - but generally it's advisable to make sure functions always return the same type to ensure they work predictably.
Similar to break
in loops or switch statements, return
also exits the function early, so no code after it in the function will run.
function add(a, b)
{
return a + b;
// no code here will run, as 'return'
// also exits the function
}
You can also conditionally exit a function early, such as by returning in an 'if' statement.
function divide(a, b)
{
if (b === 0)
{
// Log a warning message
console.log("Dividing by zero!");
// Return 0 instead of Infinity or NaN
return 0;
}
// This only runs if it did not already return
return a / b;
}
console.log(divide(1, 0));
Functions can still use return
to exit early even if they don't need to return a value - in that case return;
by itself with no value will just exit the function. (If anything tries to use the return value anyway, it will get undefined
.)
Don't add a newline after return
There's one significant pitfall to be aware of when using return
. Back in part 2 we noted that often you can omit semicolons and JavaScript will guess where they are meant to go. In part 4 we also covered how JavaScript generally doesn't care about where spaces or line breaks go. However if a line break comes after return
, JavaScript always guesses the semicolon comes immediately after return
. This is often a wrong guess and is generally regarded as a design mistake, but it's too late to change it and so we just have to live with it.
The following code snippet demonstrates code that won't work as expected.
function add(firstValue, secondValue, thirdValue)
{
// OOPS: line break after 'return'
return
firstValue + secondValue + thirdValue;
}
In this case JavaScript incorrectly guesses a semicolon goes after return
. Then nothing after a return statement is run. So it's equivalent to writing this:
function add(firstValue, secondValue, thirdValue)
{
return;
}
A function that does not provide a return value returns undefined
. So you may have thought the function would return a number with the sum of the three values, but instead it returns undefined
, just because there was a line break after return
. This is one of the reasons automatic semicolon insertion is regarded as a mistake.
So the lesson here is never to have a line break after a return
statement. Use code like the following instead.
function add(firstValue, secondValue, thirdValue)
{
// OK: no line break after 'return'
return firstValue + secondValue + thirdValue;
}