2

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

1 Answer 1

3

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.

5
  • Thanks for letting me know about restricted productions :D. It only made sense that arrow functions were some sort of exception under a category and you pointed me to it. May 29, 2020 at 11:03
  • actually this is not quite right, will edit (but can't delete as it is accepted) May 29, 2020 at 11:03
  • Oh okay yeah please edit and let me know the correct picture of it. May 29, 2020 at 11:06
  • So for normal function expression, function(){}[0] is not an invalid production according to ASI but arrow function expression is? May 29, 2020 at 11:14
  • 1
    @lakshya yes function() { }[0] is valid syntax, while () => { }[0] is not. (() => { })[0] is however. May 29, 2020 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.