Javascript Immediately invoked function Expression(IIFE)

By | April 3, 2017

Hello, While learning JavaScript, I was always confused about the weird looking syntax of executing a function. Since I am very clear about these functions in javascript I will try to explain them in this article in an easy and concise way. This weird looking function is known as IIFE(Immediately  invoked function Expression) in javascript.

Become an Expert in Programming and Web Development.View all courses!

You can read about javascript functions in this article.

Immediately Invoked Javascript Function(IIFE)

Lets first see the weirs looking function which I am talking about here in this article.

The above function is known as self executing function or Immediately invoked function expression in javascript.

But why do we need this function.

Why do we need IIFE?

Every variable declared and defined outside of a function in javascript is defined in global scope.

Suppose I have two javascript files in my project names js1.js and js1.js.

The code both of the files is shown in below snippet.

In the above code we can see I have defined a variable named “helloWorld” in js1.js and used the same variable in js2.js to show in alert box.

Now load both of the javascript files in the html page as shown below.

And once the html page is loaded we can see the alert message box with the message “HelloWorld”.

Which shows that though helloWorld variable is declared and defined in js1.js but it can be used in other file since it is defined in global scope or namespace.

But the problem here is that somebody can redefine the variable named helloWorld in the js2.js or may be somewhere else in the global namespace, which may result in ambiguity.

Now lets check another example as shown in the code below.

In the above code I have defined a function named “myFunction”. This function defined two other functions inside it.

These functions task1 and task2 cannot be accessed outside of the myFunction. We should know that a function in javascript can return another function.

That is what I am doing in last part of the above code. To access task1 and task2 outside myFunction I have assigned it two two other functions named job1 and job1. And I am returning these two function.

Now to access task1 and task2, I can  call job1 and job on the variable of function myFunction().

But all this happening in global namespace which is a very ugly thing in javascript.

To prevent all this from happening outside in global scope I should put the code in below iife.

So whenever the javascript is executed the above expression is execute automatically.


In this article I have discussed about the pollution of global namespace in javascript. And how this can be prevented by using iife.