1

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());

function y(){
    return 4; //when there's no line break it works 
};

alert(y());

//Can anyone explain this?

I always thought that JavaScript didn't care about line breaks. If you have links to ECMA official documentation on this, I'd be grateful. Thanks!

geoyws
  • 3,326
  • 3
  • 35
  • 47

4 Answers4

3

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;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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;

Gio
  • 841
  • 1
  • 5
  • 11
0

JavaScript treats a endline after return as if there was an ; So in:

return 
2;

2; is unreachable code.

And a sole return in JavaScript returns undefined. Like a function without a return does.

phylax
  • 2,034
  • 14
  • 13
0

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»

katrin
  • 1,146
  • 1
  • 13
  • 24