Automatic Semicolon Insertion (ASI) for arrow function expression vs normal function expression

Viewed 162

const log = function (x)
{
 console.log(x);
}
[1,2,3,4,5].forEach(num=>log(num))

This throws error:-

{
  "message": "Uncaught TypeError: Cannot read property 'forEach' of undefined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 16,
  "colno": 13
}

Which is because of lack of semi-colon before the array. So it's misinterpreted as:-

const log = function (x)
{
    console.log(x);
}[1,2,3,4,5].forEach(num=>log(num))

But why does the following work:-

const log = (x)=>{
 console.log(x)
}
[1,2,3,4,5].forEach(num=>log(num))

I understand that it's also a function expression as well. Is there an exception for arrow function in ASI? Or am I missing something?

1 Answers

The specification says:

When, as the source text is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true: [...]

So for ASI to happen, the syntax may be an invalid production without it. And actually it is:

  () => {}[0] // syntax error

So the Semicolon is needed here. Now why is that a Syntax error, while function () { }[0] is not? Well, the member access is defined as

  MemberExpression:
    MemberExpression [ Expression ]
    PrimaryExpression
    //...

 PrimaryExpression:
   FunctionExpression
   // no arrow function here

Why the Syntax is how it is? I don't know.

Related