Vinay Kumar

IIFE in JavaScript

If you are new to the term closure then I would suggest you to read this post before continuing because IIFE is almost similar to closures. IIFE stands for immediately invoking function expression and was coined by Ben Alman. IIFE is a JavaScript idiom and is widely used in JavaScript.

Immediately invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.
source: Wikipedia

IIFE is a function which runs as soon as it is defined. Any of the expression defined below can be used to create IIFE . I will be making use of first expression for the entire blog post.

(function () {
   // Code
 })(); // Note: () are outside

(function () {
   // Code
 }()); // Note: () are inside

From the above expression we can infer that by wrapping a closure in grouping operator () and immediately using the function expression () will result in IIFE.

One of the points to be kept in mind is that in JavaScript a function will have access to those variables which are initialized before the function declaration. This holds true for even closures and IIFE. Now before diving into an example we shall address on how to pass arguments to IIFE. It's through the grouping operator ().

(function () {
   // Code
 })("John", lastName="Doe");

But wait! why is the example having declaration ("John", lastName="Doe") and not ("John", "Doe"); ? The reason for it is the next step which is to access the passed arguments inside the closure. There are two ways, first is through function parameter and second is by using the variable directly inside the closure.

(function (firstName) {
   
   var fullName = firstName+lastName;
   
   // For example purpose nothing is returned
   console.log(fullName);
 
})("John", lastName="Doe");

Another interesting thing is when a variable is initialized inside () then it can also be accessed outside of the IIFE.

(function (firstName) {
   var fullName = firstName+" "+lastName;
   
   // For example purpose nothing is returned
   console.log(fullName);
 
})("John", lastName="Doe");

console.log(lastName); //Output: Doe

Finally let's dive into an example. Below example uses IIFE to create something similar to singleton class module pattern.