1

Whats wrong with this code?

function test() {

   (function(){
      console.log('1')  
   })()

   (function(){
      console.log('2')
   })()
}

test()

http://jsfiddle.net/VvaCX/

AlaskaKid
  • 197
  • 1
  • 2
  • 9

2 Answers2

8

You're missing the semi-colons from the end of each function call...

function test() {

    (function(){
        console.log('1');  
    })();

    (function(){
        console.log('2');
    })();
}

test();

Here is a JSFiddle of the working code if you need to test it. For example, in Chrome you can right-click > inspect element > and switch to the "Console" tab

Thanks to @pimvdb for pointing out what this actually attempts to do when you do not have the semi-colons:

It is currently trying to pass the second function as an argument to the result of the first.

musefan
  • 47,875
  • 21
  • 135
  • 185
  • 4
    +1 It is currently trying to pass the second function as an argument to the result of the first. – pimvdb Dec 15 '11 at 17:11
  • 1
    Finally, a clear semantic argument for the use of semicolons in JavaScript! I've been looking for this for ages! – Platinum Azure Dec 15 '11 at 17:13
  • JS's wishy-washy attitude toward semicolons can mask problems like that illustrated here. Can also work against you in the other direction, as described by Crockford on page 102 of The Good Parts. – Christopher Dec 15 '11 at 17:16
  • @PlatinumAzure: are you sure you looked in the right places? http://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript#answer-1169596 – PeeHaa Dec 15 '11 at 17:23
2

I've just tested. You NEED your semi-colons.

This works:

function test() {

    (function(){
        console.log('1');
    })()

    (function(){
        console.log('2');
    })()
}

test()

Firebug shows the error at console.log('1'),

mauris
  • 42,982
  • 15
  • 99
  • 131