5

People often talk about JavaScript's nasty ASI (Automatic Semicolon Insertion), and often cite this example...

function a() {
    return [
        'a',
        'b',
        'c'
    ];
}

function b() {
    return
    [
        'a',
        'b',
        'c'
    ];
}

console.log(a(), b());
// ["a", "b", "c"] undefined

Is there really a semicolon being inserted after return in b(), or does the JavaScript grammar state that the return value must explicitly be stated after it (i.e. no \n)?

alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    You can find your answer on following link.. http://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion – Tarun Nagpal Mar 08 '11 at 12:15

2 Answers2

3

I don't think there's a semicolon "inserted". It's just that there's a parse ambiguity there, and the resolution is to treat the "return" and the following expression as two separate statements. I understand why it makes sense from a purely grammatical standpoint, but it seems like a weird decision in the specific case of the "return" statement as the decision is guaranteed to leave a never-executed orphan expression statement dangling after it.

I wonder how many aggregate SO rep points that trick has generated?

edit 04 Apr 2014 — technically that decision to split the statement into two statements is called "semicolon insertion". Nobody actually sees the inserted semicolon; it's a figment of the parser's imagination :) The effect is the same whatever you call it.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

There's nothing in the spec that says a return value has to be on the same line as a return statement, it's just bad semi-colon insertion.

EMMERICH
  • 3,424
  • 2
  • 18
  • 14
  • 5
    Doesn't this quote say otherwise? *return [no LineTerminator here] Expression;* from the [ECMASpec](http://es5.github.io/x5.html). – alex Aug 14 '14 at 23:34