Fork me on GitHub

Ahad Bokhari

IIFE Pattern

Edit   ·   words

The definition of an IIFE in JavaScript is simply a self executing function and design pattern in JavaScript that can be used to avoid variable hoisting from within blocks and protects against polluting the global environment and retaining privacy defined with the given function.

In short, the IIFE “iffy” pattern is one of the top three modern ways JavaScript users are programming their applications.
Of course we all remember all to well that variables are global, unless we use var and wrap them as a function:

var foo = 4;
qux = 100;

function bar() {
  a = 5;
  var b = 60;

Let’s take a quick peak on how to use them effectively in your every day code:

Avoiding Globals Like the Plague

Here we’ll use an IIFE with encapsulated members and no global variables:

(function() {                                                                                      

// private count variable
  var count = 0;

  // private method _add

  var _add = function(a, b) {
    document.writeln(a + b + "- count = " + count);
  // private method _sub

  var _sub = function(a, b) {
    document.writeln(a - b + "- count = " + count);
  // return public method add and sub as a JavaScript Object literal

  return {
    add : _add,
    sub : _sub

// Create an object of Mathlibrary class
var mathObj = new Mathlibrary();

// Call methods add and sub on the mathObj object
mathObj.add(150, 100);
mathObj.sub(150, 100);

Using an IIFE in Angular Modules

You can use the simple IIFE approach for module syntax like so:

(function () {

  'use strict';

  function MainCtrl ($scope, SomeFactory) {
    this.doSometing = function () {

    .controller('MainCtrl', MainCtrl);


##The Module Pattern
We can use an IIFE to attach an environment to module data:

var namespace = function() {
        var myArr = []; // not visible outside
        for(var i=0; i<10; i++)="" {="" myarr.push(i);="" }="" return="" get="" values()="" myarr;="" };="" }();="" console.log(namespace.values);="" [0,1,2,3]="" <="" code="">


An IIFE is not an alternative to $(document).ready(function(){}). The alternative is $(function(){});

(function($) {
  console.log('logs immediately');
    console.log('logs after ready');