The IIFE pattern

June 8, 2015

IIFE, which stands for Immediately Invoked Function Expression, is a common JavaScript design pattern aimed to protect a module’s scope from the environment in which it is placed.


There are two ways of writing such pattern, each perfectly valid, so just pick your favorite.

(function(){ /* code */ }()); // Crockford's way
(function(){ /* code */ })(); // But this is also fine

Crockford doesn’t like parens on the IIFE’s outside — because they “look like dog balls”

Function expressions can be named or anonymous, and so do IIFEs

(function IIFE(){ /* code */ })(); // Named IIFE
(function(){ /* code */ })(); // Anonymous IIFE

Named function expressions are generally more preferable especially for debugging, and no, it won’t pollute your global scope.


Why the parentheses wrap

An immediately invoked function expression need to be wrapped inside parens to avoid the parser to throw an error by thinking it encountered an anonymous function declaration instead.

// Function expression VS Function declaration
var fn = function(){}; // Expression
function fn(){}; // Declaration

Benefits

The main benefit of the IIFE pattern is local scoping and that’s why it is used by most popular libraries (jQuery, Backbone.js, etc).

Another small benefit relies on the ability to pass common global objects (like window, document, jQuery, etc) to an IIFE in order to reference them locally from within the IFEE’s local scope. This reduce the number of scope lookups and increase performances.

(function IIFE((window, document, $){
  // ...
}(window, document, window.jQuery));

For more details on the IIFE pattern read Ben Alman’s original post.

comments powered by Disqus