Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No semicolon before [] is causing error in JavaScript

var a = [1, 2, 3, 4];
var b = [10, 20, 30, 40];
console.log([a, b].length)
[a, b].some(function(x) {
  x.push(x.shift())
});

I was extremely surprised today when this code caused

[a,b].some(function(x){ x.push(x.shift()) });
      ^
TypeError: Cannot call method 'some' of undefined

Obviously the JavaScript 'auto semicolon insertion' is not working as expected here. But why?

I know you might recommend to use ; everywhere to avoid something like that, but the question is not about whether it is better to use ; or not. I would love to know what exactly happens here?

like image 808
exebook Avatar asked May 21 '13 07:05

exebook


People also ask

What happens if semicolon is missing in JavaScript?

The JavaScript exception "missing ; before statement" occurs when there is a semicolon ( ; ) missing somewhere and can't be added by automatic semicolon insertion (ASI). You need to provide a semicolon, so that JavaScript can parse the source code correctly.

Is it necessary to put semicolon in JavaScript?

Semicolons are not required for JavaScript programming, nevertheless I advice you to use it. It makes your code more readable and is actually a good practice, and almost all cool programming languages uses it. Take a stand and use it, it's up to you now!

What does missing semicolon before statement mean?

As the name implies, the Missing Semicolon Before Statement error is typically thrown when a semicolon ( ; ) was forgotten somewhere in the code.


1 Answers

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.

like image 161
Dan M Avatar answered Oct 22 '22 10:10

Dan M