skip to content

In JavaScript, why does a function return undefined when the object literal after return starts on the next line, and how do you fix it?

level: middleimportance: must knowfreq 55%

answer

  1. a line break the grammar forbids
  2. automatic semicolon insertion
  3. restricted production
  4. the next line is unreachable
  5. open the expression on the same line

basics

~20 s

Automatic semicolon insertion ends the statement: the grammar forbids a line break between return and its expression, so the parser reads a bare return and the next line never runs. Start the expression on the return line.

solid answer

~50 s

`return` is a restricted production: the grammar forbids a line terminator between the keyword and its expression. When the parser finds one, automatic semicolon insertion (ASI) adds a semicolon right there, so `return` with an object on the next line becomes `return;`, and the function returns `undefined`. The next line is still parsed but never runs. Nothing throws at that point, so the bug surfaces far away, often as `Cannot read properties of undefined` in the caller. A one-key literal like `{ ok: true }` parses as a block holding a label, while `{ ok: true, n: 1 }` is not a valid block, so that version fails the whole script with a `SyntaxError`. The fix is to begin the expression on the same line, with `return {` or `return (`. The restriction covers the gap after the keyword, so ordinary line breaks inside the expression are safe.

code

javascript · 17 lines
javascript
function a() {
  return
    { ok: true };
}
function b() {
  return {
    ok: true,
  };
}
function c() {
  return (
    { ok: true }
  );
}
console.log(a()); // undefined
console.log(b()); // { ok: true }
console.log(c()); // { ok: true }

go deeper

for a junior

Recall the rule in one line: never put a line break straight after return. Know that the function then returns undefined, and that return followed by an opening parenthesis is the safe multi-line form.

for a middle

Explain the mechanism by name: return is a restricted production, so a line terminator there triggers insertion even though the next token would be legal. Predict the block-versus-literal outcome for one and two keys.

for a senior

Trace the symptom back from a distant TypeError in a caller, and name what catches it before review: an unreachable-code lint rule and a formatter that prints the bare return. Say why a semicolon style does not protect you.

for a principal

Style arguments about semicolons miss this point, since this hazard exists in either style. Spend the standard on tooling that flags unreachable code in CI, rather than on review vigilance.

## The symptom A function looks as if it returns an object, but every caller receives `undefined`: ```javascript function getStatus() { return { ok: true }; } console.log(getStatus()); // undefined ``` No error appears where the mistake is. The failure shows up later, in a caller that reads a property, as `Cannot read properties of undefined`. That distance is what makes the bug expensive to find. ## What the parser does JavaScript's grammar requires a semicolon at the end of certain statements, `return` among them, and **automatic semicolon insertion (ASI)** supplies it in defined situations. One of those situations is the **restricted production**: a place where the grammar forbids a line terminator. Between `return` and its expression is such a place. So the parser does this: 1. It reads the `return` token. 2. It sees a line terminator where the grammar allows none. 3. It inserts a semicolon, which completes the statement as `return;`. 4. It parses the following line as a separate statement that can never run. Writing your own semicolon at the end of the object line changes nothing, because the insertion happens earlier, straight after `return`. The bug therefore also appears in code whose style uses semicolons everywhere. ## What the next line parses as The unreachable line still has to parse, and the outcome depends on its shape, because after a complete statement a `{` opens a **block**, not an object literal. | Line after `return` | How it parses | Result | |---|---|---| | `{ ok: true };` | Block with the label `ok` and the expression `true` | Function returns `undefined` | | `{ a, b };` | Block with a comma expression | Function returns `undefined` | | `[1, 2, 3];` | Array expression statement | Function returns `undefined` | | `a + b;` | Expression statement | Function returns `undefined` | | `{ ok: true, n: 1 };` | Not a valid block | `SyntaxError`, and the script does not load | | `{ 'ok': true };` | Not a valid block | `SyntaxError`, and the script does not load | Adding a second key to a literal can therefore turn a silent wrong value into a parse failure, which confuses people who have only seen one of the two. ## The fix, and what is safe The restriction covers only the gap between `return` and the **first token** of the expression. After that, line breaks follow the normal rules: - `return {` with the keys on the following lines works, since the literal has started. - `return (` with the value on the following lines works, and this is the usual form for long expressions. - `return a +` with `b` on the next line works, since the expression is not complete at the line break. - `return a` with `+ b` on the next line also works, since `+` can continue the expression and so nothing triggers an insertion. Comments deserve care. A line comment after `return` is followed by a line terminator, so insertion happens. A block comment containing a line break behaves like a line terminator too, so a multi-line comment between `return` and the value also returns `undefined`. A block comment that stays on one line is harmless. ## The other restricted places The same rule applies wherever the grammar forbids a line terminator: - postfix `++` and `--`: `a = b` followed by `++c` on the next line is `a = b; ++c;`, not `b++`; - `break` and `continue` before a label: the label on the next line is not attached; - `throw` and `yield` before their expressions; - `=>` after an arrow function's parameters, which is a `SyntaxError` on the next line; - `async` before `function`, and `using` before its first identifier. ## Catching it The parser accepts this code, so habit alone is a weak defence. An unreachable-code rule in a linter flags the line after a bare `return`, and a formatter that re-prints the code shows `return;` on its own line, which makes the mistake visible in review. Some engines also print a console warning about a statement after `return`. A type checker that sees the declared return type helps too, since the function now returns nothing.

  • In JavaScript, why does `return {` with the keys on later lines work, when the object literal still spans several lines?
    The restriction covers only the gap between `return` and the first token of the expression. Once `{` sits on the `return` line, the parser is inside an object literal, and line breaks inside it are ordinary white space. No insertion happens, because every following token is allowed there. The same reasoning makes `return (` safe.
  • Where else does JavaScript forbid a line break the way it does after `return`?
    Before postfix `++` and `--`, between `break` or `continue` and a label, after `throw` and `yield`, between an arrow function's parameters and `=>`, after `async` before a function, and after `using` before its identifier. Depending on the place, the result is a silently different program, as with `a = b` then `++c`, or a `SyntaxError`, as with `=>` on a new line.
  • Does adding a semicolon to the end of the line after `return` fix this JavaScript bug?
    No. The automatic semicolon is inserted straight after `return`, before the parser reaches that line, and your own semicolon only ends the following statement, which is unreachable anyway. So the function still returns `undefined`. Moving the first token of the expression onto the `return` line is what fixes it.

  • Semicolon insertion only fires when the next token would be a syntax error.
  • Ending the next line with a semicolon stops the bare return from happening.
  • A line break anywhere inside the returned object literal triggers the same bug.
  • A multi-line block comment between return and the value cannot trigger insertion.
  • The unreachable line is ignored, so its contents can never cause a syntax error.
  • The line after a bare return throws an unreachable-code error at runtime.