Sub topic 18
The Line Break After return Pitfall
This chapter assumes you know how return works and how a function returns undefined when it has no return value. Both are covered in "Returning Values and the Implicit undefined." You should also be comfortable with object literals and arrow functions.
The bug in this chapter produces no error and no warning at runtime. The function silently returns undefined. It usually shows up when someone reformats a long return expression so it reads better.
The Symptom
Here is the classic case:
function getConfig() {
return
{
debug: true
};
}
console.log(getConfig()); // undefinedThe author meant to return { debug: true }. The function returns undefined instead, and the object literal never runs.
Why It Happens: Automatic Semicolon Insertion
Automatic semicolon insertion (ASI) is the set of rules the JavaScript parser uses to add semicolons you left out. Most of the time ASI only adds a semicolon when the code would otherwise fail to parse. A few statements are different. The specification calls them restricted productions, and it forbids a line break at certain points inside them. If a line break appears at one of those points, the parser ends the statement there, even when the next line could have continued it.
return is one of these. A line terminator directly after the return keyword ends the statement. The parser therefore reads the example above as:
function getConfig() {
return;
{
debug: true;
}
}That explains why the code runs at all. The braces on the following lines are not parsed as an object literal. They are a block statement, debug: is a label, and true is an expression statement inside that block. All of this is legal and never executes, because the function has already returned.
Edge Cases Worth Knowing
Sometimes it becomes a syntax error
The silent version depends on the leftover code happening to be a valid block. Add a second property and it stops being valid:
function getConfig() {
return
{
debug: true,
verbose: false
};
}
// SyntaxError: Unexpected token ':'Inside a block, debug: true, verbose is a label followed by a comma expression, and the parser then hits : false, which cannot appear there. A loud failure like this is better than a silent one, but whether you get it depends on what the object contains. Don't count on it.
Only the break right after return matters
The restriction covers only the gap between return and the start of the expression. Once the expression has started on the return line, later line breaks follow the normal rules:
function total(a, b) {
return a
+ b; // continues the expression
}
console.log(total(2, 3)); // 5When the parser reaches the end of the return a line, the next token + can continue the expression, so it inserts no semicolon. Multi-line ternaries, method chains and && chains are safe in the same way, as long as their first token sits on the return line.
Other restricted productions
The same rule applies to several other keywords and operators:
| Construct | Line break at the restricted point | Result |
|---|---|---|
| `return` + newline + expression | after `return` | Returns `undefined` |
| `throw` + newline + expression | after `throw` | `SyntaxError` (illegal newline after throw) |
| `break` / `continue` + newline + label | before the label | Label ignored |
| `yield` + newline + expression | after `yield` | Yields `undefined` |
| `x` + newline + `++` | before postfix `++`/`--` | `++` applies to the next line |
| `(a)` + newline + `=> a` | before `=>` | `SyntaxError` |
| `async` + newline + `function` | after `async` | `async` treated as an identifier |
throw is the friendly case, because the engine refuses to parse it. return and yield are the dangerous ones, because both have a valid meaning on their own.
Fixes
Start the expression on the return line
Put the first token of the value on the same line as return. For an object literal, that token is the opening brace:
function getConfig() {
return {
debug: true,
verbose: false
};
}
console.log(getConfig()); // { debug: true, verbose: false }Use parentheses for long expressions
To put a long expression on its own lines, open a parenthesis on the return line. That way the expression has already started when the line break comes:
function canEdit(user, doc) {
return (
user.active &&
(user.role === "admin" || doc.ownerId === user.id)
);
}
console.log(canEdit({ active: true, role: "viewer", id: 7 }, { ownerId: 7 })); // trueJSX code uses return ( for exactly this reason.
Arrow functions with implicit returns
An arrow function with an expression body has no return keyword, so this pitfall cannot happen there. The restricted point moves to the => instead. A line break after => is fine. A line break before it is a syntax error. Object literals still need the parentheses described in the previous chapter:
const toPoint = (x, y) =>
({ x, y });
console.log(toPoint(1, 2)); // { x: 1, y: 2 }Letting Tools Catch It
You don't have to rely on remembering the rule. Tools catch it for you:
- ESLint reports the dead block with the
no-unreachablerule, which is enabled ineslint:recommended. - TypeScript reports error 7027, "Unreachable code detected." The
allowUnreachableCodeoption controls whether this is an error, a suggestion, or silent. - Prettier reformats
returnfollowed by a newline and{intoreturn;followed by a separate block. The bug becomes visible in the diff.
Exercises
Exercise
What does f() return, and why? function f() { return\n 42; }
Show answer
It returns undefined. The line break after return makes ASI end the statement as return;. The line 42; becomes an unreachable expression statement.
Exercise
Does this function return 10 or undefined? function g() { const a = 4, b = 6; return a\n + b; }
Show answer
It returns 10. The expression a starts on the return line. At the line break, the next token + can continue the expression, so no semicolon is inserted and the function returns a + b.
Exercise
This code throws "SyntaxError: Unexpected token ':'". Explain the error and rewrite the function so it returns the object. function opts() { return\n { mode: "dark", size: 2 }; }
Show answer
The parser inserts a semicolon after return and reads the braces as a block. mode: is a label and "dark", size is a comma expression, so the colon after size is invalid. Fix: function opts() { return { mode: "dark", size: 2 }; }. If you want the object on its own lines, open the brace or a parenthesis on the return line.
Exercise
Why is a line break after throw less dangerous than one after return?
Show answer
throw must have an expression, so throw followed by a newline is a SyntaxError and the engine rejects the code at once. return with no expression is valid, so the code runs and silently returns undefined.