Last Updated: February 25, 2016
·
2.107K
· shaybenmoshe

Use Immediately-Invoked Function Expressions

An immediately-invoked function expression (IIFE) is an anonymous function that runs immediately when it is defined.
The format for such functions is

(function() {
    // More code here...
}());

Note: The purpose of the outer parentheses is to get the JavaScript parser to treat this as an expression rather than a declaration. There are several other alternatives, but this is the most common.

As you can see, the function will be immediately called, since we have added () in the end of its deceleration.

The primary is advantage of IIFE is scoping.
In JavaScript only functions have scopes, thus an IIFE has it's own scope and declarations within it won't affect the global scope.
For this reason, it is very common to wrap libraries and modules with IIFE.