Search code examples
javascriptself-invoking-function

What are the differences between these three types of module pattern?


1)function () { 
    // code here...

}();

2)(function () { 
    // code here...

})();



3)(function () { 
    // code here...

}());

What are the differences (especially third variant)? Are they all the same?


Solution

  • First one gives a syntax error. Second and third versions define a anonymous function and immediately execute it. Second and third versions are also called Immediately Invoked Function Expressions.

    You might also encounter another version which looks like this. This is equal in functionality to 2nd and 3rd version but it just negates the return value.

    !function() {
       //some code
    }()