AlaskaKid
AlaskaKid

Reputation: 307

2 following self-invoking functions don't work

Whats wrong with this code?

function test() {

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

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

test()

http://jsfiddle.net/VvaCX/

Upvotes: 1

Views: 88

Answers (2)

musefan
musefan

Reputation: 48445

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.

Upvotes: 8

mauris
mauris

Reputation: 43619

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'),

Upvotes: 2

Related Questions