Can Anyone Explain Why Linebreaks Make Return Statements Undefined In Javascript?
Solution 1:
Here are the ECMAScript rules for Automatic Semicolon Insertion. The relevant section is:
When a continue, break, return, or throw token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after the continue, break, return, or throw token.
In short, your code is parsed as if it were:
return;
2;
Solution 2:
Unlike most other languages, JavaScript tries to "fix" your code by adding semicolons where it thinks you have forgotten them.
Return statements are such a case - if there is a linebreak after a return statement, it will be interpreted as return;
Solution 3:
JavaScript treats a endline after return
as if there was an ;
So in:
return2;
2;
is unreachable code.
And a sole return
in JavaScript returns undefined
. Like a function without a return
does.
Solution 4:
JS gramma from mozilla http://www-archive.mozilla.org/js/language/grammar14.html#N-Statement
Note:
the OptionalSemicolon grammar state can sometimes reduce to «empty»
Post a Comment for "Can Anyone Explain Why Linebreaks Make Return Statements Undefined In Javascript?"