Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

JavaScript IIFE Design Pattern

3.74/5 (17 votes)
15 Jun 2017CPOL7 min read 44.2K  
Immediately Invokable Function Expressions in JavaScript

IIFE (Immediately Invokable Function Expressions)

This post gives a small introduction about Singleton Pattern in JavaScript.

The post offer you more topics on Object Oriented JavaScript Design.

IIFE (Immediately Invokable Function Expression) is a important concept in JavaScript. it is a commonly used Design Pattern which is used to wrap set of variables and functions which cannot be accessed outside the enclosed scope.

These are Anonymous Function that is wrapped inside a set of paranthesis and is called immediately.

The common advantage of IIFE is that any "Function or Variable" defined inside IIFE, cannot be accessed outside the IIFE block, thus preventing global scope from getting polluted. Also helps us manage memory in an efficient manner.

In order to understand the concept of IIFE, we need to understand the difference between the following:

  1. Function Definition
  2. Function Expression

Function Definition

Lets look at a very simple "Function Definition":

function demoFunction(){

  alert("This is the function Definition");

}

So the simplest way to understand "Function Declaration" is that, it starts with "function" keyword.

The biggest benefit of function definition over Function Expressions is that they are "Hoisted" by the JavaScript Compiler. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code by the compiler.

Hoisting is when a JS declaration is lifted (“hoisted”) to the top of it’s scope. What this really means is that a variable or function isn’t necessarily declared where you think it is. Function Definition and Variable Declaration are always Hoisted on the top of the Function Scope or Global Scope.

This can be understood by this small example:

demoFunction();

function demoFunction(){

  alert("Function is already Hoisted");

}

Here we can see that the user is trying to access "demoFunction()" even before the compiler reaches its "Function Definition", In this case function will be executed. It will be called by the compliler and shall output a alert message. The function definition is hoisted on the top of the Scope by the compiler, therefore it is available even before its Function Definition during script execution.

The concept of Hoisting does not adher to Function Expressions. Function Expressions are never Hoisted.

Function Expressions has got its own benefits which we shall be evaluating in a short while.

Function Expressions

"Function Expression" would be any function defined which does start "function" keyword.

Another way to define a function expression is to assign a function to a variable.

This is another common way to create a function apart from the "Function Declaration" Syntax above.

var demoFunction = function(){

  alert("This is function Expression");

};

Since the above function does start the keyword "function", its a "Function Expression"

The above code assigns a function definition to a variable "demoFunction".

This would mean that the variable "demoFunction" shall now represent a function definition.

The function can now be called using following line of code: "demoFunction()"

What are IIFE ...

IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

(function(){

  alert("Function does not start with keyword "function", therefore Function Expression");

})();

This is a simple function in which anything written inside the function block shall be executed immediately.

In the above example, once the code is executed, following events occur:

  1. A function Instance is created.
  2. Function is Executed.
  3. Function created is discarded.

The variable and functions that were declared in the scope of IIFE are available for garbage collection, once the IIFE is executed. Hence managing Memory in an efficient manner and ensures that the function and variables do not bind itself to the global scope.

In order to understand, we can break down the above code into 2 parts:

  1. Creating Function Expression
  2. Invoking the Function Expression

Part One: (Function Expression)

Breaking the code further, we will get a "Function Expression" enclosed within "Brackets".

When a function definition does not contain "function" keyword in the starting of an executable line of code, it is called Function Expression.

In this code we can see that the function definition starts with "(", therefore its a function Expression.

(function(){

  alert("Function enclosed within Simple Brackets, therefore Expression");

});

This is a simple Function Expression.

Similarly, IIFE it does starting the keyword "function", it is also a "Function Expression".

So, we first get a "Function Expression" that contain some code enclosed in it.

(function(){

  alert("Function enclosed within Simple Brackets, therefore Expression");

});

The next step will be calling the "Function Expression" just like any other function using"()".

** Note: Important difference between Function Expression and Function Declaration is:

"Function Declaration can be Hoisted, but Function Expressions cannot be Hoisted".

Part Two: (Function Invocation)

Once the function Expression is defined, it is invoked using "()", in the same manner as we call a function.

(function(){

  alert("Function Expression Invoked using () at the end");

})();

// Here the function call in made using '()'

Once the Function Expression is invoked, the code inside the function expression shall execute.

So the above discussion about the IIFE can be compiled as:

A Function Expression immediately invoked using "()".

So here we can see that a IIFE is a "Function Expression" called immediately after its definition.

Breaking IIFE into parts:

So the above IIFE code can be rewritten as:

var functionExpression = (function(){

  alert("Function Expression assigned to variable.");

});

functionExpression();

This code can be analysed in the following way:

  1. "Function Expression" is created and stored in a variable "functionExpression"
  2. Function Expression is called just like any other function.

Why do we require IIFE

Benefits of IIFE are:

1. Avoids Global Scope from getting Polluted

One of the main reason to create IIFE is to avoid global scope from getting polluted.

Lets understand this with a simple example:

(function(){

  var sampleVariable = "test Variable";

  var sampleVariable = function(){

    alert("Function does not start with keyword "function", therefore Function Expression");

  }

})();

Here in the above function, we have created a "Variable" and a "Function", this variables and function are enclosed within an IIFE Expression, therefore the scope of the variable and function lies within the IIFE. These variables and functions are not added to Global Scope.

We may use IIFE when we want to define some functions and variable that are just required to be executed for a single time on a page.

Lets say that we have a device and we have to set the Theme according to the device that is used by the user. Here when the user logs into our Application, we need to check the Device just once since the device wont change. In such a case, variables and functions required to detect the Device wont be required once executed. In such a case wee would not like to add these variables and function to the global scope and consume Browser space. So these functionalities can be enclosed within an IIFE, so that once executed, all the variables and function defined for the same can be made available for Garbage Collection.

2. Manage Browser Memory

If the functions are such that they require single execution, as specified in above example, we need not to add those function and variable to the gobal scope. Adding them to global scope would consume space on the Browser Memory.

So once these functions are executed, we would like them to be Garbage Collected.

Following Events occur when a IIFE is encountered:

  1. A function Instance is created.
  2. Function is Executed.
  3. Function created is discarded.

When the IIFE is executed, the required functions and variables are created, used and once IIFE has finished execution, they are available for Garbage Collection, Hence freeing the Browser Memory.

3. Minification Optimization

IIFE also helps us with the minification. Since we can paas values to the arguments in IIFE, we areable to reduce the name of each global object to a one letter word.

The Example shall help you understand it better:

(function(w){

  alert('Window object is now renamed to "w"');

})(window);

Here we can see that the "Window" object is passed as to the IIFE, "Window" object is passed to an argument "w". So now the window object shall be refered as "w" instead of "window", hence helping us with the minification process.

Passing Arguments to IIFE Function

We can simply pass arguments to IIFE in the following manner:

var Name = "Mayank";

var Age = 27;

(function(name, age){

  alert("Name: " + name);

})(Name, Age);

Here the Arguments are enclosed within "()" brackets.

In the above example we can see:

  1. We have variable "Name" and "Age" at Global Level
  2. We need to pass these variable to "IIFE",
  3. IIFE accepts 2 parameters "name" and "age".
  4. Global Variable "Name" and "Age" are enclosed withing the Function Invokation Brackets.
  5. "Name and Age" shall now be available to IIFE as arguments passed from outside enviroment.

**Note:

Please do not confuse between the following implementation of IIFE.

Both shall represent the same IIFE Expression.

Please see the difference in placement of Brackets "()" while function invocation.

(function(){

  alert("Name: " + name);

})()

The above implementation of IIFE is same as the one below. The onle difference is the placement of brackets during function Invokation

(function(){

  alert("Name: " + name);

}());

IIFE is an amazing Design Pattern offering Lots of Benefits. Try using IIFE in your Code to Optimise it Further. Hope the article shall provide help to people who are trtying to understand the concept.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)