Immediately Invoked Function Expression (IIFE) in JavaScript3 min read

In JavaScript, an Immediately Invoked Function Expression (IIFE) is a JavaScript function expression that executes as soon as it defined.

(function iifeFunction() {
   console.log('Hello World');
})();

This function will print to the console ‘Hello World’ right after we define it. Writing IIFE is similar to write a regular function, but just with some little extra steps. In the first place, we just need to wrap the function we want to invoke right after its definition by enclosing parentheses:

(function foo() {
// some code
}) 

Then, we use another pair parentheses to call the function, the number of arguments you pass in should correspond to the numbers of parameters in the function:

// call the function foo with no parameter right after its declaration
(function foo() {
// some code
})() // this pair of parentheses will make the function called immediately

// call the function bar with 2 parameters
(function bar(name, age) {
console.log("Hello, my name is " + name + ", I am " + age + " years old");
})("Brian", 28);

You can also create an IIFE without giving it a name:

//  Self-Executing Anonymous Function
(function () {
 // some code
})()

The purpose of surrounding parentheses is to make the function as a function expression, not a function declaration. If you assign the function to a variable then there is no need for the enclosing paratheses because this function is already a function expression:

var a = function() { 
    console.log('works fine');
}(); // works fine

Variables inside the IIFE are treated as local variables or private, they are only accessed in their scope which is defined inside this function and cannot be exposed outside of their scope. This is an important thing we need to keep in mind.

(function myFunc() {
   var commonName = "Jessica";

})();
commonName; 
// VM676:5 Uncaught ReferenceError: commonName is not defined at <anonymous>:5:1

Basically, the IIFE will be executed immediately right after its definition as we stated before. Hence, when a function is done with its execution, its scope, and also data preoccupied inside it is also effectively vanished (check out this article to learn how JavaScript actually works). Then we cannot access its variables because of this fact.

Even though there is no keyword like public or private in JavaScript, however, with this interesting property, IIFE is a great way to encapsulate your data from being directly exposed to the outside world.

We cannot expose the variables inside the IIFE directly, but in essence, we still need to access its data at some points, and of course, there are some indirect admittances to help us accomplish that.

First off, if we just want to return an expression such as a variable, an object, etc…We just simply return what we desire like this:

(function myFunction() {
   var myName = "Brian";
   return myName;
})() // "Brian"

(function anotherFunction() {
   var myName = {name: "Brian", age: 20}
   return myName;
})() // {name: "Brian", age: 20}

A more powerful way of accessing the IIFE data is by using Closure. Fundamentally, a closure is an inner function that keeps references to its parent’s scope even after its parent function has returned. For example:

var myVar = (function closureInsideIIFE() { 
    var x = 20;
    function add(num) {
       x = x + num;
    }
    return {
       publicMethod: function(num) {
          add(num);
          console.log(x);
       }
    }
})()

myVar.publicMethod(5); // 25

Let’s break down what’s really happening here:

  • We define a function named closureInsideIIFE, there are a private variable and a private function add and also inside this IIFE, we return an object which has a single method publicMethod.
  • Then on line 12, we instantly invoke this closureInsideIIFE function and assign its returned value to the variable myVar.
  • Here after this closureInsideIIFE function has returned, the myVar will hold the value of an object which contains a method named publicMethod.
  • On line 14, we call the method publicMethod and pass a value 5. Then look back at line 8, even the closureInsideIIFE function effectively disappeared, but we still can access to its add function thanks to the power of closures. The value 5 then will be passed to the add function, and then this function increases the value of x.
  • To make a little observation, we log out the value of the variable x after adding 5 to it, then we got 25, unsurprisingly.

Because of publicMethod acting as a closure, we not only can flexibly access the data of the IIFE but also we can update its values as well.

Previous Article
Next Article
Every support is much appreciated ❤️

Buy Me a Coffee