Sub topic 17
Implicit Returns in Arrow Functions
This chapter assumes you can write arrow functions such as (x) => x * 2, that you know a function without return produces undefined, and that you are comfortable with object literals and array methods like map and filter. The focus is narrow: how an arrow function decides whether to return a value automatically, and the parsing rules that catch people out.
Two Kinds of Arrow Body
An arrow function's body takes one of two forms, and the character right after => decides which one you get.
- An expression body is a single expression with no braces. The function evaluates it and returns the result. This is the implicit return.
- A block body starts with
{. It behaves like a normal function body: statements run in order, and nothing is returned unless you writereturn.
const doubleExpr = (x) => x * 2; // expression body
const doubleBlock = (x) => { return x * 2; }; // block body with explicit return
const doubleBroken = (x) => { x * 2; }; // block body, no return
console.log(doubleExpr(4)); // 8
console.log(doubleBlock(4)); // 8
console.log(doubleBroken(4)); // undefinedThe last version is a very common bug. It usually shows up when you expand a one-liner into braces to add a console.log and forget to add return.
Returning Object Literals
Since { right after => always starts a block, you cannot return an object literal by writing it directly. Put parentheses around it. The opening ( tells the parser an expression follows, and inside that expression the braces are read as an object literal.
const toPoint = (x, y) => ({ x, y });
const broken = (x, y) => { x, y };
console.log(toPoint(1, 2)); // { x: 1, y: 2 }
console.log(broken(1, 2)); // undefinedWhy does broken run without an error? The parser treats { x, y } as a block that contains the expression statement x, y. The comma operator evaluates both values and discards the result. Nothing is returned, so the call gives undefined.
Other unparenthesised object literals fail in different ways:
const labelled = () => { name: "Ana" };
console.log(labelled()); // undefined
// const twoProps = () => { name: "Ana", age: 30 };
// SyntaxError: the parser reads "name:" as a label, then fails at ", age:"In labelled, name: is parsed as a statement label, which is legal JavaScript that almost nobody uses on purpose, and "Ana" is an expression statement. Add a second property and the code stops parsing at all. A silent undefined is worse than a syntax error, because the code runs and the bad value appears somewhere else.
What Counts as a Single Expression
An expression body can be any expression, including some that look like control flow:
| Want | Expression form |
|---|---|
| Choose between values | `(n) => n >= 0 ? "positive" : "negative"` |
| Fallback value | `(user) => user.nickname ?? user.name` |
| Call another function | `(id) => fetchUser(id)` |
| Build an array | `(a, b) => [a, b]` |
| Build an object | `(name) => ({ name, createdAt: Date.now() })` |
| Template string | `(name) => `Hi, ${name}`` |
Statements cannot appear in an expression body. That rules out if, for, const declarations, throw (until throw expressions land in the language), and try. If you need any of them, switch to a block body and write return explicitly.
Nested ternaries are legal, but they get hard to read quickly. When a body needs more than one decision, a block body with guard clauses is usually clearer than a chain of ? :.
Multi-line Expression Bodies
An expression body does not have to fit on one line. Wrap it in parentheses and spread it out:
const users = [
{ first: "Ana", last: "Silva", age: 34 },
{ first: "Bo", last: "Chen", age: 17 },
];
const summaries = users.map((u) => ({
fullName: `${u.first} ${u.last}`,
isAdult: u.age >= 18,
}));
console.log(summaries);
// [ { fullName: "Ana Silva", isAdult: true },
// { fullName: "Bo Chen", isAdult: false } ]Line breaks have rules. You may break the line after =>, and the body still belongs to the arrow. You may not break the line between the parameter list and =>. That is a syntax error.
const ok = (x) =>
x + 1;
console.log(ok(1)); // 2
// const bad = (x)
// => x + 1; // SyntaxError: unexpected token '=>'This is unrelated to the return-followed-by-newline problem covered in another chapter. An expression body has no return keyword, so automatic semicolon insertion cannot cut it off after =>.
Implicit Returns in Callbacks
Implicit returns suit array callbacks, where the return value is the point:
const prices = [12, 5, 40, 8];
const withTax = prices.map((p) => p * 1.2);
const cheap = prices.filter((p) => p < 10);
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(withTax); // [14.4, 6, 48, 9.6]
console.log(cheap); // [5, 8]
console.log(total); // 65Here the brace mistake hurts most. prices.filter((p) => { p < 10; }) returns [], because every callback returns undefined, which is falsy. map with the same mistake produces an array of undefined.
The opposite problem also happens. An implicit return can hand back a value you never meant to return. Array.prototype.push returns the array's new length, so (x) => list.push(x) returns a number. That does no harm in forEach, which ignores return values. It can confuse APIs that act on the returned value. For example, some event and cleanup APIs treat a returned function or false as meaningful. When a callback should return nothing, use a block body or the void operator:
const log = [];
const record = (msg) => void log.push(msg);
const recordBlock = (msg) => { log.push(msg); };
console.log(record("a")); // undefined
console.log(recordBlock("b")); // undefined
console.log(log); // ["a", "b"]When to Prefer a Block Body
Use an expression body when the function is a pure transformation that fits in one readable expression. Use a block body when:
- you need statements: variables, loops,
try, orthrow - you want guard clauses with early returns
- the function runs only for its side effects, so a returned value would mislead
- you need a breakpoint or a
console.login the middle. Converting to a block is fine, but remember to addreturn.
An async arrow with an expression body follows the same rules. async (id) => ({ id }) returns a Promise that resolves to the object. The parentheses are still required.
Exercise
What does each call log, and why? const a = (n) => { n * n }; const b = (n) => ({ n }); const c = (n) => { value: n }; followed by console.log(a(3), b(3), c(3));
Show answer
It logs undefined { n: 3 } undefined. a has a block body with no return statement. b wraps its object literal in parentheses, so the expression body returns { n: 3 }. c has a block body in which value: is a label and n is an expression statement, so it also returns undefined.
Exercise
Rewrite const tags = items.map((item) => { label: item.name, id: item.id }); so that it works. Explain why the original fails.
Show answer
Use const tags = items.map((item) => ({ label: item.name, id: item.id }));. In the original, { after => starts a block, label: is read as a statement label, and the comma followed by id: cannot be parsed, so the line throws a SyntaxError.
Exercise
A teammate writes const evens = nums.filter((n) => { n % 2 === 0; }); and always gets an empty array. Give two fixes.
Show answer
Either remove the braces to get an expression body, nums.filter((n) => n % 2 === 0), or keep the block and return the value, nums.filter((n) => { return n % 2 === 0; }). The original callback returns undefined, which is falsy, so filter keeps no elements.