IIFE ( Immediately Invoked Functions Expression) in Javascript

As a javascript programmer we all know in javascript there is concept of anonymous function, those who do not know the concept of anonymous function please go through the concept before reading IIFE. IIFE in javascript is an anonymous function which is self invoked. The below code snippet is the syntax to create an IIFE.

IIFE can be written in the several ways. Below code snippet present the common convention followed by developers to write an IIFE expression. This is also known as the Douglas Crockford’s style.

Code snippet:


IIFE expression can be used to avoid variable hoisting from within block, protect against polluting the global environment and allow public access to method while retaining the privacy of variables.

The primary reason to use an IIFE is to obtain data privacy. Because JavaScript’s var scopes variables to their containing function, any variables declared within the IIFE cannot be accessed by the outside world.

(function () {
var foo= “hello”;
console.log(foo); // Outputs: “Hello”
// ReferenceError: foo is not defined

We can achieve the same thing as IIFE by declaring a function and invoked the function as below code snippet.

function imediatlyInvokedFunction(){
 var greet= ‘hello world’;

If we can achieve the same behavior as IIFE with the above code snippet then why we need IIFE?

Answer is the above code as some disadvantages. First one is we can call the imediatlyInvokedFunction as many times from our code, but IIFE can be executed only once. Second one is imediatlyInvokedFunction function declaration takes up names in the global namespace this could leads to a name collision.

You can point out that how can we pass arguments to the IIFE which is declare in the parent scope chain of the IIFE. We can achieve the same with below code snippet where we can inject the variable or object or function as dependency to the IIFE.

var greet = ‘hello World’;
(function($, _, msg){
})(JQuery, undescore, greet,);

As you can see in the above code base that the JQuery and underscore object is injected apart from your custom variable/objects/functions greet etc.

I would encourage you all to run/play around the below code snippet and try to understand the behavior of IIFE and what is will print in the console.

var foo=10;



var foo = 20;


Thank you. Thats all I about IIFE.

Like what you read? Give Swapan Shaw a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.