return on its own line returns undefined
return on its own line returns undefined in JavaScript means javaScript inserts a semicolon after a return that ends its line, so the function returns undefined and the value below is never reached.
How do I fix return on its own line returns undefined?
In JavaScript, a return followed by a line break returns undefined. Automatic semicolon insertion turns it into return;, so the value on the next line never runs. Start the value on the same line as return: write return { on one line, or return ( followed by the expression and a closing ).
- 1. Line break after returnLook for return alone at the end of a line. Move the opening { or ( up onto that line.
- 2. Unreachable code warningsTurn on the ESLint rule no-unreachable. It flags code after a return that ends early.
- 3. Formatter settingsRun Prettier, which keeps the value on the return line and wraps long expressions in parentheses.
What does return on its own line returns undefined mean?
Automatic semicolon insertion (ASI) treats return followed by a line break as return;. The object or expression on the next line becomes unreachable code. Linters flag it; the language does not.
Why does return on its own line returns undefined happen?
1. Returning an object on the next line
The opening brace must be on the return line.
Breaks
return
{
ok: true
};Works
return {
ok: true
};2. Returning a long expression
Wrap it in parentheses that start on the return line.
Breaks
return
a && b && c;Works
return (
a && b && c
);How to find it in your own code
Never put a line break directly after return. Start the value, a bracket or a parenthesis on the same line, and use a linter (no-unreachable) to catch it.
Try it: fix this bug
mediumgetStatus(200) returns undefined.
function getStatus(code) {
return
{
ok: code < 400
};
}Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.