4

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?

  • Presumably that’s interpreted as calling the array with a function then calling the result of that without any parameters. Could you expand on *”won’t work”*? – jonrsharpe Oct 02 '17 at 16:08
  • It's the basic issue with JavaScript automatic semicolon insertion. Your first sample of code is *not* a case where JavaScript will add a semicolon, so it's as if the blank line isn't there. – Pointy Oct 02 '17 at 16:08
  • @jonrsharpe Click on "run this snippet" and see the errors being spitted out. –  Oct 02 '17 at 16:10
  • That is the problem with JavaScript which most people complain about, in case of ambiguity, instead of raising error, it makes a lot of assumptions. Watch Gary Bernhardt's WAT talk, if you haven't already and you will get the idea. https://www.youtube.com/watch?v=SB3VFaznrcs – sid-m Oct 02 '17 at 16:13
  • @gaazkam you have just found the reason why is everyone advising to use semicolons everywhere – Tamas Hegedus Oct 02 '17 at 16:14
  • https://stackoverflow.com/a/17978926/1823841 – palaѕн Oct 02 '17 at 16:15
  • I don’t see that on the mobile app, but looking at the answers it seems my guess was correct. – jonrsharpe Oct 02 '17 at 16:42

1 Answers1

3

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.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112