Sub topic 14
Returning Values and the Implicit undefined
This chapter assumes you can declare and call functions, work with arrays and objects, and read template literals. The earlier chapters covered what goes into a function. This one covers what comes out: the return statement, the value a caller receives, and the undefined that JavaScript supplies when you don't return anything.
What return Does
A return statement does two things at once:
- It evaluates the expression after it, if there is one.
- It ends the function immediately and hands that value back to the caller.
No code after an executed return runs. The call expression, such as square(4), takes on the returned value, so you can store it, pass it on, or use it inside a larger expression.
function square(n) {
return n * n;
console.log("never runs"); // unreachable
}
const result = square(4);
console.log(result); // 16
console.log(square(3) + square(2)); // 13
console.log(`Area: ${square(5)}`); // "Area: 25"A function returns exactly one value per call. If you need to send back more than one piece of data, you wrap the pieces in an array or object. A later chapter covers that pattern.
The Three Ways a Function Produces undefined
Every function call in JavaScript produces a value. If you don't choose one, the caller gets undefined. This happens in three situations:
| Situation | Example body | Caller receives |
|---|---|---|
| Execution reaches the closing brace without a `return` | `{ console.log(x); }` | `undefined` |
| A bare `return;` with no expression | `{ return; }` | `undefined` |
| `return` with an expression that evaluates to `undefined` | `{ return obj.missing; }` | `undefined` |
function noReturn() {
const x = 1 + 1; // computed, then discarded
}
function bareReturn() {
return;
}
function returnsMissing() {
const obj = {};
return obj.missing;
}
console.log(noReturn()); // undefined
console.log(bareReturn()); // undefined
console.log(returnsMissing()); // undefinedThe caller cannot tell these cases apart. "Returns nothing" and "returns undefined" mean the same thing in JavaScript. A function is never "void" in the sense of producing no value at all. Its result just happens to be undefined.
Common Error: Using the Result of a Side-Effect Function
A side effect is any change a function makes outside itself, such as logging, writing to a variable, or mutating an object. Functions written only for their side effects usually return undefined. Storing their result is a frequent bug.
function addTax(order) {
order.total = order.subtotal * 1.2; // mutates, returns nothing
}
const order = { subtotal: 100 };
const updated = addTax(order);
console.log(order.total); // 120
console.log(updated); // undefined
// updated.total would throw: TypeError: Cannot read properties of undefinedThe TypeError shows up at the line that uses the value, which may be far from the function that forgot to return. When you see "Cannot read properties of undefined", check whether the value came from a function call that has no return.
Built-in methods have the same trap. console.log returns undefined. Array.prototype.forEach returns undefined. Array.prototype.push returns the new length and not the array.
const list = [1, 2];
const pushed = list.push(3);
console.log(pushed); // 3 (the new length, not [1, 2, 3])
const doubled = list.forEach((n) => n * 2);
console.log(doubled); // undefined; use map to build a new array
console.log(list.map((n) => n * 2)); // [2, 4, 6]Common Error: return Inside a Callback
A return exits only the function it appears in, which is the innermost one. Inside a callback, it returns from the callback and not from the outer function.
function hasNegative(nums) {
nums.forEach((n) => {
if (n < 0) return true; // returns from the arrow function only
});
// outer function falls off the end
}
console.log(hasNegative([1, -2, 3])); // undefined
function hasNegativeFixed(nums) {
for (const n of nums) {
if (n < 0) return true; // exits hasNegativeFixed
}
return false;
}
console.log(hasNegativeFixed([1, -2, 3])); // true
console.log(nums => nums.some((n) => n < 0)); // logs the function itself
console.log([1, -2, 3].some((n) => n < 0)); // trueUse a for...of loop when you need to return from the outer function partway through. Use methods like some, find, or every when they already express the question you are asking.
Edge Cases Worth Knowing
return in a finally block
A return inside finally overrides any earlier return or thrown error from the try block. This is almost always a mistake, so keep finally for cleanup only.
function surprising() {
try {
return "from try";
} finally {
return "from finally";
}
}
console.log(surprising()); // "from finally"Constructors called with new
When you call a function with new, the rules change. A missing return, or a returned primitive, gives back the newly created object. A returned object replaces it.
function Point(x) {
this.x = x;
return 42; // primitive: ignored under new
}
function Weird() {
this.x = 1;
return { replaced: true }; // object: replaces this
}
console.log(new Point(5)); // Point { x: 5 }
console.log(new Weird()); // { replaced: true }
console.log(Point(5) === undefined); // false, without new it returns 42Classes follow the same rule for their constructor. In practice, constructors should not return anything.
Where return is not allowed
return is only valid inside a function body. At the top level of a script or ES module it is a SyntaxError. The later chapters cover the remaining special cases: arrow functions with expression bodies return without the keyword, a line break directly after return makes it return undefined, and async functions wrap their return value in a Promise.
Choosing What to Return
Decide what a function returns as part of its signature, just as you decide its parameters:
- Functions that compute something should return the result and avoid side effects where possible.
- Functions that perform an action may return
undefined, but returning something useful, such as the updated object or a success flag, often makes them easier to chain and test. - "Not found" should have one consistent representation.
undefinedmatches built-ins likeArray.prototype.find.nullsignals an intentional empty result. Pick one and use it throughout.
Exercise
What does this code log, and why? function check(n) { if (n > 10) { return "big"; } else if (n > 5) { "medium"; } } console.log(check(20), check(7), check(1));
Show answer
It logs big undefined undefined. For 20, the first branch returns "big". For 7, the expression "medium" is evaluated but never returned, so the function falls off the end and returns undefined. For 1, no branch matches and the function also reaches the end of its body, returning undefined.
Exercise
A teammate writes const names = users.forEach((u) => u.name); and then gets a TypeError on names.length. Explain the cause and give a fix.
Show answer
forEach always returns undefined, whatever its callback returns, so names is undefined and reading .length throws. Use map, which returns a new array of the callback's return values: const names = users.map((u) => u.name);.
Exercise
What does new Box() evaluate to if function Box() { this.size = 3; return "small"; }? What does Box() return when called without new (in non-strict mode)?
Show answer
new Box() evaluates to the new object { size: 3 }, because a returned primitive is ignored when the function is called with new. Calling Box() without new returns the string "small". In non-strict mode it also sets size on the global object, because this refers to the global object there.