0

I read some article said following 5 cases has no ASI. The first 4 cases are easy to understand but I don't get the 5th case. Why is the 5th case valid ?

   //1. treated as plus operation
   a = b
   +a

   //2. treated as minus operation
   a = b
   -a

   //3. treated as division operation
   a = b
   /something/.test(a)

   //4. treated as function invocation
   a = b
   (function () {})()

   //5. treated as property access
   a = b
   [1, 2, 3].forEach() 

Another example for that is the function expression

a = function() {

}
[1,2,3].forEach(function(item) {

});

//It will be interpreted as following,  but why is this valid at all?

a = function() {
}[1,2,3].forEach(function(item) {

});

Why is it valid for function express at all ? Why just add ASI for square bracket?

PS, I did read What are the rules for JavaScript's automatic semicolon insertion (ASI)? before I asked my question. But I don't see that answer my question about square bracket, especially for function expression

Qiulang
  • 5,733
  • 4
  • 47
  • 82
  • Because `a = b[1, 2, 3].forEach()` is a syntactically-valid series of expressions. ASI generally kicks in on when the result would otherwise be a syntax error. ASI is an *error-correction* mechanism (per Brendan Eich). – T.J. Crowder Sep 09 '18 at 09:14
  • But what about the function expression I mentioned. Is that also valid ? – Qiulang Sep 09 '18 at 09:15
  • BTW I did read the SO you marked as duplicated but I still don't get it and that is why I asked my question. – Qiulang Sep 09 '18 at 09:16
  • What, specifically? If the expression is valid when whitespace is removed, ASI generally doesn't apply. ASI != insert a `;` in front of every newline – T.J. Crowder Sep 09 '18 at 09:19
  • Can you help me understand why a = function() { }[1,2,3].forEach(function(item) { }); is a valid expression. – Qiulang Sep 09 '18 at 09:20
  • 1
    It is a bit fun. :-) `function(){}[1, 2, 3]` is evaluated like this: The `[]` are a property accessor, and functions are objects. What's inside the `[]` uses the comma operator, which is one of JS's more unusual operators: It evaluates both its left-hand and right-hand operands, and results in the value the right-hand operand yielded. So `[1, 2, 3]` is effectively `[3]`. So that's `function(){}[3]` -- reading the `3` property from the function. Then the expression goes on to try to use the `forEach` property of that as a function. It fails at runtime, but it's *syntactically* correct. – T.J. Crowder Sep 09 '18 at 09:24
  • OH Thanks! Now I understand. BTW, I am still thinking about re-word my question to make my question not a duplicated one. – Qiulang Sep 09 '18 at 09:29
  • FWIW, I wouldn't bother. But you *could* change it to "Why is (that expression) syntactically valid?" – T.J. Crowder Sep 09 '18 at 09:33

0 Answers0