Sub topic 12
Returning Values and the Implicit undefined
This chapter assumes you can declare and call functions and that you know the difference between parameters and arguments. Up to now the focus has been on data going into a function. This chapter covers the value that comes back out.
What return does
A return statement does two things at once:
- It stops the function immediately. No code after it runs.
- It hands a value back to the caller. The call expression evaluates to that value.
function square(n) {
return n * n;
console.log("never runs"); // unreachable
}
const result = square(5);
console.log(result); // 25
console.log(square(2) + 1); // 5A call such as square(5) is an expression, so you can use it anywhere a value fits: in an assignment, in arithmetic, or as an argument to another call.
The implicit undefined
Every JavaScript function returns a value. If the function never reaches a return statement, or reaches a bare return; with no expression, the caller receives undefined.
function logOnly(message) {
console.log(message);
}
function maybe(flag) {
if (flag) return "yes";
return; // bare return
}
console.log(logOnly("hi")); // logs "hi", then undefined
console.log(maybe(true)); // "yes"
console.log(maybe(false)); // undefinedThe table shows which value each ending produces.
| How the function ends | Value the caller receives |
|---|---|
| `return expr;` | The value of `expr` |
| `return;` | `undefined` |
| Runs off the closing brace | `undefined` |
| Throws an error | No value; the error propagates |
Common errors
The most frequent bug is forgetting return in a function that computes something. The function runs fine, but the result is lost:
function total(prices) {
prices.reduce((sum, p) => sum + p, 0); // computed, then discarded
}
console.log(total([1, 2, 3])); // undefinedAdding return before prices.reduce(...) fixes it. When a value turns up as undefined with no obvious cause, check every path through the function. One if branch that falls through without returning is enough to cause it.
The value undefined is also what you see when you accidentally use the result of a side-effect function, for example const x = arr.forEach(...). The forEach method always returns undefined.
Exercise
What does this code log, and why? function check(n) { if (n > 10) { return "big"; } if (n > 5) { "medium"; } } console.log(check(12), check(7), check(2));
Show answer
It logs "big undefined undefined". check(12) reaches return "big". check(7) evaluates the string "medium" but never returns it, so the function runs off the end and returns undefined. check(2) matches no branch and also returns undefined.
Exercise
Is there any difference in what the caller receives between a function that ends with return; and one that has no return statement at all?
Show answer
No. Both give the caller undefined. A bare return only lets you leave the function early.