Understanding IIFE in JavaScript
Learn about IIFE in JavaScript with practical examples
Introduction
A common pattern in JavaScript is to execute a function as soon as it is declared. This is known as an immediately invoked function expression or IIFE pattern, which will cause a function to be immediately executed or invoked.
In this article, we will learn about IIFE in JavaScript with practical examples. Let’s get right into it.

What is an IIFE?
IIFE stands for immediately invoked function expression, it is a pattern in JavaScript that is used to execute a function as soon as it is declared.
Here is an example of IIFE:
(function () {
console.log("Chirp, chirp!");
})(); // this is an anonymous function expression that executes right away
// Outputs "Chirp, chirp!" immediately
Note that the function has no name and it is not stored in a variable. The two parentheses ()
at the end of the function expression cause it to be immediately executed or invoked.
When to use IIFE?
Sometimes, you accidentally pollute the global scope by unknowingly giving the same name to variables and functions as global variable and function names. For example, when there are multiple JavaScript files in your application written by multiple developers over a period of time. So in this situation, there is a high chance of having the same names of functions and variables.
Consider the following example of two different JavaScript files included in a single web page.
The file index.js
:
var userName = "Bill";
function display(name)
{
alert("index.js: " + name);
}
display(userName);
The file app.js
:
var userName = "Steve";
function display(name)
{
alert("app.js: " + name);
}
display(userName);
If you run these two JavaScript files on your web page, you will find out that only the file app.js
that is executed because it’s included after the file index.js
in the HTML. So, JavaScript always considers the last definition if two functions or variables have the same name.
IIFE solves this problem by having its own scope. It is restricting functions and variables to become global. As a result, the functions and variables declared inside IIFE will not pollute the global scope even if they have the same name.
To solve the problem above that we had with the two JavaScript files, we can wrap all the code inside these two files in an IIFE.
Have a look at the following example:
(function () {
var userName = "Steve";
function display(name)
{
alert("index.js: " + name);
}
display(userName);
})();
As you can see, this is a good situation to use IIFE. The global scope won’t be affected anymore.
Conclusion
IIFE does not create unnecessary global variables and functions. It also helps to organize the code and makes it maintainable. You can learn more about it from the Mozilla documentation.
Thank you for reading this article, I hope you found it useful.