Why do I have to put a semicolon before a self executing anonymous function?

Viewed 261

Most of the cases Javascript permits us to omit a semicolon in the end of a statement. However, interestingly, not in this case:

var x = [5, 'asdf']

(function() {
  window.alert("Yay!")
})()

This won't work, unless we put one semicolon in the end of the statement preceding the anon function:

var x = [5, 'asdf'];

(function() {
  window.alert("Yay!")
})()

Now it works perfectly.

What obscure rule governing implied semicolons in the ends of statements prescribes that in this case this one semicolon is not implied?

1 Answers

Uncaught TypeError: [5,\"asdf\"] is not a function

According to the error it considers that your [5, 'asdf'] is an function name, and you tries to execute it passing the parameters. If we join them in one line, you can see that it is similar to the function call with passed parameter as function

[5, 'asdf'](function() { window.alert("Yay!") })

So putting semicolon says to the compiler that the statement ends, and the next line is another statement which is IIFE.

Related