No semicolon before [] is causing error in JavaScript

When I’m worried about semicolon insertion, I think about what the lines in question would look like without any whitespace between them. In your case, that would be:

console.log([a,b].length)[a,b].some(function(x){ etc });

Here you’re telling the Javascript engine to call console.log with the length of [a,b], then to look at index [a,b] of the result of that call.

console.log returns a string, so your code will attempt to find property b of that string, which is undefined, and the call to undefined.some() fails.

It’s interesting to note that str[a,b] will resolve to str[b] assuming str is a string. As Kamil points out, a,b is a valid Javascript expression, and the result of that expression is simply b.

Leave a Comment