Search code examples
javascriptself-invoking-function

JavaScript self-invoking functions


Possible Duplicate:
Difference between (function(){})(); and function(){}();
Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?

I just wondered whether there is a difference (regarding the functionality) between these two examples:

1st

(function foo() {
console.log("bar")
})()

2nd

(function foo() {
console.log("bar")
}())

Both seem to work fine ...

Thanks!


Solution

  • They are exactly the same. There is no difference whatsoever between the two in terms of efficiency, output, or use. Using either one is a matter of preference.

    Though there is a shorter variation of the two forms commonly used by JS minfiers. That is, logical NOT-ing the function expression and calling it:

    !function() {
        console.log( x );
    }();​