Skip to content Skip to sidebar Skip to footer

Can Anyone Explain Why Linebreaks Make Return Statements Undefined In Javascript?

This has been the source of my pain for many hours. Can anyone explain why this is the case? function x(){ return //when there's a line break it doesn't work 2; }; alert(x

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?"