What is an IIFE (Immediately Invoked Function Expression) in JavaScript? What are the Pros and Cons?

February 13, 2023

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

What Is an IIFE (Immediately Invoked Function Expression)?

Immediately Invoked Function Expression (IIFE) in JavaScript refers to an anonymous function that is executed immediately when it is defined, and is usually used to create a local scope to avoid global pollution.

IIFE Syntax

(function () {
  // Code to be executed
})();

In this expression, the function definition and function call parentheses are together to ensure that the function will only be executed once, instead of being defined and executed multiple times. In this enclosing scope, neither variables nor functions pollute the global environment.

Benefits of Immediately Invoked Function Expression

Creating a Local Scope

By using IIFE, you can create a local scope and avoid the pollution of global variables. In an IIFE, local variables can only be accessed inside the IIFE, not outside of it, as shown in the following code:

// Global scope
var globalVariable = "global variable";

(function () {
  // Local scope inside IIFE
  var localVariable = "local variable";
  console.log(localVariable); // local variable
})();

console.log(localVariable); // ReferenceError: localVariable is not defined
console.log(globalVariable); // global variable

Avoiding Naming Conflicts

IIFE can create a separate namespace for variables to avoid conflicts between function names and variable names, as shown in the following code:

// Global scope
var globalVariable = "global variable";

(function () {
  // Local scope inside IIFE
  var globalVariable = "local variable inside IIFE";
  console.log(globalVariable); // local variable inside the IIFE
})();

console.log(globalVariable); // global variable

Modular Programming

IIFE can divide the code into independent modules, which facilitates the management and maintenance of the code. In "What Is JavaScript Modules?",it was mentioned that IIFE was used as a modular practice at the beginning of front-end modularization when developing and there was no front-end modular tool. In the following code example, we create two modules through two IIFEs, each with its own variables and functions inside, and the role of IIFE is to create a local scope to avoid variable pollution. Next, we add the corresponding module object to the window to realize the disclosure of the module. When in use, we can directly access the functions in the module through the window object, realizing modular programming.

// Module1
(function () {
  var module1Variable = "I am a variable in module 1";
  function module1Function() {
    console.log(module1Variable);
  }
  window.module1 = {
    module1Function: module1Function,
  };
})();

// Module2
(function () {
  var module2Variable = "I am a variable in module 2";
  function module2Function() {
    console.log(module2Variable);
  }
  window.module2 = {
    module2Function: module2Function,
  };
})();

// Usage
module1.module1Function(); // I am a variable in module 1
module2.module2Function(); // I am a variable in module 2

Improve code execution efficiency

IIFE can execute immediately when defined, avoiding storing and calling of unnecessary functions and improving program execution efficiency.

Disadvantages of IIFEs

  1. Difficult to Maintain As the code becomes more complex, the code inside the IIFE can become large and difficult to read and maintain.

  2. Bad for Re-use IIFEs are typically used only once and cannot be easily re-used, making them inconvenient when they need to be called multiple times.

  3. Increased Code Complexity Using IIFEs can make the code more complex, especially if the code size is large.

Classic Interview Questions - setTimeout, Scope, IIFE

The following is a classic interview question about setTimeout, Scope, and IIFE:

What is the output of the following?

for (var i = 1; i <= 5; i++) {
  setTimeout(function () {
    console.log(i);
  }, 0);
}

Answer

// Immediately output five 6s
6;
6;
6;
6;
6;

Explanation

Variables declared with var are function-scoped, not block-scoped in JavaScript. Therefore, after the loop ends, i has the value 6, and each setTimeout callback refers to the same i variable, outputting 6 each time.

Further reading: What is Scope and Scope Chain in Javascript?

Solution

To output 1, 2, 3, 4, 5 every second, there are two solutions:

  1. IIFE

    Here, an immediately invoked function (IIFE) and an anonymous function are used to form a private scope (equivalent to closure), the variables in the private scope and the variables in the global scope do not conflict with each other; at this time, the value of i passed in each for loop will be stored in memory as a private variable, waiting for the for loop to execute After completion, follow the task queue output.

    for (var i = 1; i <= 5; i++) {
      (function (i) {
        setTimeout(function () {
          console.log(i);
        }, i * 1000);
      })(i);
    }
    
  2. Use let to declare variables:

    Since the variables declared with let are block-scoped, we can use let to declare the i variable inside the loop. This way, each iteration of the loop has its own i variable, and the output will be 1, 2, 3, 4, 5.

    for (let i = 1; i <= 5; i++) {
      setTimeout(function () {
        console.log(i);
      }, i * 1000);
    }
    
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee