A Wonky Return Statement In Javascript
Solution 1:
Because in Javascript, a statement can be terminated by a newline instead of a semicolon. The semicolon is essentially inserted automatically, but only where the result can be a full statement.
return;
is valid on its own, but then your function returns nothing and your "value";
has no side-effects.
On the other hand, your first example simply cannot be parsed this way because the line ends in the middle of a parenthesis.
These rules are described in §7.9.1 in the ECMA-262 standard document.
Solution 2:
Automatic Semicolon Insertion is the cause. When the expression to return starts on a separate line to the return
keyword, a semicolon is inserted after the return
statement. Semicolons are optional in many cases but this is not one of them
So
function returnValue() {
return"value";
}
ends up becoming/being interpreted as
function returnValue() {
return; // <- semicolon inserted here"value";
}
which results in undefined
being returned. One way to fix this is to start the value to return on the same line as return
.
There are rules for when automatic semicolon insertion happens, summarized as
The resulting practical advice to ECMAScript programmers is:
- A postfix ++ or -- operator should appear on the same line as its operand.
- An Expression in a return or throw statement should start on the same line as the return or throw token.
- A label in a break or continue statement should be on the same line as the break or continue token.
Solution 3:
Javascript automatically inserts a semicolon after return
.
Read more: What are the rules for JavaScript's automatic semicolon insertion (ASI)?
Solution 4:
That's because JavaScript automatically adds a semicolon to the end of the return line, so in the second example, it's essentially as if it said just return;
.
Post a Comment for "A Wonky Return Statement In Javascript"