Search code examples
javascriptself-invoking-function

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/


Solution

  • 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.