Sub topic 6
Arrow Function Syntax and Implicit Returns
Arrow functions are the shortest way to write a function expression in JavaScript. The short syntax has a few traps. You can parse a body the wrong way, return undefined when you meant to return an object, or hit a syntax error because of where a line break or an operator sits. This chapter covers the grammar of arrow functions: parameter lists, the two body forms, implicit returns, and the edge cases that catch experienced developers.
This chapter assumes you know basic JavaScript syntax, const and let, object literals, and function expressions from the previous chapter. How arrows treat this, arguments, and new is covered in later chapters. Here we focus only on how arrows are written and what they return.
The Basic Shape
An arrow function is a parameter list, the => token, and a body. Like any function expression, it produces a value that you usually assign to a variable or pass as an argument.
const double = function (n) {
return n * 2;
};
const doubleArrow = (n) => {
return n * 2;
};
const doubleShort = n => n * 2;
console.log(double(4)); // 8
console.log(doubleArrow(4)); // 8
console.log(doubleShort(4)); // 8All three functions do the same thing. The third version drops the parentheses around its single parameter, the braces, and the return keyword. Most of the rules in this chapter explain when you can drop each of those parts.
Parameter Lists
You can omit the parentheses around the parameters in exactly one case: a single plain identifier. Every other case needs parentheses.
| Parameters | Syntax | Parentheses required? |
|---|---|---|
| None | `() => 42` | Yes |
| One plain name | `x => x + 1` | No (optional) |
| Two or more | `(a, b) => a + b` | Yes |
| Default value | `(x = 1) => x` | Yes |
| Rest parameter | `(...xs) => xs.length` | Yes |
| Destructuring | `({ name }) => name` | Yes |
| Trailing comma | `(a, b,) => a + b` | Yes |
Destructured parameters come up often with array methods, so they are worth seeing in action:
const users = [
{ name: 'Ada', age: 36 },
{ name: 'Alan', age: 41 }
];
const names = users.map(({ name }) => name);
const pairs = [[1, 2], [3, 4]].map(([a, b]) => a + b);
console.log(names); // [ 'Ada', 'Alan' ]
console.log(pairs); // [ 3, 7 ]Two Kinds of Body
The token right after => decides how JavaScript parses the body.
- A concise body is a single expression. The function returns the value of that expression implicitly, with no
returnkeyword. - A block body starts with
{. It is an ordinary function body made of statements, and it returnsundefinedunless areturnstatement runs.
const concise = (a, b) => a + b;
const block = (a, b) => {
const total = a + b;
return total;
};
const forgotReturn = (a, b) => {
a + b;
};
console.log(concise(2, 3)); // 5
console.log(block(2, 3)); // 5
console.log(forgotReturn(2, 3)); // undefinedThe forgotReturn bug is common when you refactor. You start with a concise body, add braces to insert a console.log for debugging, and forget to add return. The function still runs and throws no error. It just returns undefined, and the problem shows up somewhere downstream.
Returning Object Literals
Because a { right after => always starts a block body, you cannot return an object literal by writing it directly. The parser reads the braces as a block and reads key: value as a label (a name attached to a statement, normally used with break and continue) followed by an expression.
const wrong = () => { id: 1 };
const right = () => ({ id: 1 });
console.log(wrong()); // undefined
console.log(right()); // { id: 1 }wrong is valid code. It contains a block with a statement 1 labeled id, and it returns nothing. If you add a second property, the result can no longer be parsed as a block, so you get a syntax error instead of a silent bug:
// SyntaxError: Unexpected token ':'
// const broken = () => { id: 1, name: 'Ada' };Wrapping the literal in parentheses makes it an expression, so the concise-body rule applies. This pattern is everywhere in code that builds new objects without changing the old ones:
const withId = (obj, id) => ({ ...obj, id });
const toEntry = ([key, value]) => ({ key, value });
console.log(withId({ name: 'Ada' }, 7));
// { name: 'Ada', id: 7 }
console.log(Object.entries({ a: 1 }).map(toEntry));
// [ { key: 'a', value: 1 } ]Multi-Line Concise Bodies
A concise body can span several lines as long as it is one expression. Parentheses make the boundaries clear, and conditional (ternary) expressions and method chains fit this form well.
const describe = n => (
n === 0 ? 'zero'
: n > 0 ? 'positive'
: 'negative'
);
const activeNames = users => users
.filter(u => u.active)
.map(u => u.name)
.sort();
console.log(describe(-3)); // negative
console.log(activeNames([
{ name: 'Zed', active: true },
{ name: 'Amy', active: false },
{ name: 'Bob', active: true }
])); // [ 'Bob', 'Zed' ]Once you need a variable, an if statement, a loop, or try/catch, switch to a block body. Packing logic into a nested ternary just to keep the implicit return hurts readability for no gain.
Syntax Edge Cases
No Line Break Before =>
The grammar forbids a line terminator between the parameter list and =>. A line break after => is fine.
// SyntaxError: Unexpected token '=>'
// const bad = (a, b)
// => a + b;
const good = (a, b) =>
a + b;
console.log(good(1, 2)); // 3Arrows Have Low Precedence
An arrow function parses at the same level as an assignment expression, so it cannot be the direct operand of most operators. You must wrap it in parentheses.
const userHandler = null;
// SyntaxError: Malformed arrow function parameter list
// const handler = userHandler || () => 'default';
const handler = userHandler || (() => 'default');
console.log(handler()); // default
const result = (() => 'ran immediately')();
console.log(result); // ran immediatelyThe same low precedence explains the concise body. Everything after => up to the end of the expression belongs to the body. So x => x + 1, 5 in a context that allows a comma expression means "the arrow, then 5". It does not mean "an arrow that returns 5". When in doubt, add parentheses.
Currying Reads Right to Left
Arrows associate to the right, so a => b => a + b means a => (b => a + b). This makes curried functions and function factories short to write:
const add = a => b => a + b;
const addTen = add(10);
const hasRole = role => user => user.roles.includes(role);
const admins = [
{ name: 'Ada', roles: ['admin'] },
{ name: 'Bob', roles: ['user'] }
].filter(hasRole('admin'));
console.log(add(2)(3)); // 5
console.log(addTen(5)); // 15
console.log(admins[0].name); // AdaDiscarding a Return Value With void
An implicit return always returns something. Sometimes the caller cares about the return value. For example, a callback that returns false can have a special meaning, or a typed API may expect undefined. The void operator evaluates an expression and produces undefined, so the function stays one line without leaking a value:
const saved = [];
const save = item => saved.push(item);
const saveQuietly = item => void saved.push(item);
console.log(save('a')); // 1 (push returns the new length)
console.log(saveQuietly('b')); // undefined
console.log(saved); // [ 'a', 'b' ]Async Arrows
Put async before the parameter list. The single-parameter shortcut still works, and an implicit return becomes the promise's resolved value.
const fetchDouble = async n => n * 2;
const fetchPoint = async (x, y) => ({ x, y });
fetchDouble(21).then(v => console.log(v)); // 42
fetchPoint(1, 2).then(p => console.log(p)); // { x: 1, y: 2 }Common Errors at a Glance
| Symptom | Likely cause | Fix | Column | Column |
|---|---|---|---|---|
| Function returns `undefined` | Block body without `return` | Add `return`, or use a concise body | ||
| `map` yields `undefined` items | `=> { key: value }` parsed as a label | Wrap the object: `=> ({ key: value })` | ||
| `Unexpected token ':'` | Multi-property object read as a block | Wrap the object in parentheses | ||
| `Unexpected token '=>'` | Line break before `=>` | Move `=>` to the parameter line | ||
| `Malformed arrow function parameter list` | Arrow used as an operand of `\ | \ | `, `&&`, or `?:` condition | Wrap the arrow in parentheses |
| Callback returns an unexpected value | Implicit return of a side-effect call | Use a block body or `void` |
Exercise
What does each call log, and why? const a = () => { value: 1 }; const b = () => ({ value: 1 }); const c = x => { x * 2 }; console.log(a(), b(), c(3));
Show answer
It logs undefined { value: 1 } undefined. In a, the braces form a block body that contains a statement 1 labeled value, so the function returns nothing. In b, the parentheses make the braces an object literal in a concise body, so the object is returned. In c, the braces form a block body that computes x * 2 and throws the result away, because there is no return.
Exercise
Rewrite this function as a single-expression arrow named tag, keeping its behavior: function tag(label) { return function (item) { return { label: label, item: item }; }; }
Show answer
const tag = label => item => ({ label, item }); The outer arrow returns the inner arrow (arrows associate to the right). The inner arrow needs parentheses around the object literal so it is returned instead of being parsed as a block. Shorthand properties replace label: label and item: item.
Exercise
Why is const run = cb || () => {}; a syntax error, and what is the corrected line?
Show answer
An arrow function parses at assignment-expression precedence, so it cannot appear directly as the right operand of ||. Wrapping it fixes the error: const run = cb || (() => {});