IIFE

  • This lesson explains IIFE and its role in JavaScript scope management.
  • Introduction to IIFE

    In JavaScript, functions are usually:

    • Defined first

    • Called later

    But sometimes, we need a function that:

    • Runs immediately

    • Runs only once

    • Does not pollute the global scope

    For such cases, JavaScript provides a special concept called IIFE.

    What is an IIFE ?

    IIFE stands for:

    Immediately Invoked Function Expression

    An IIFE is a function that is executed immediately after it is created.

    Simple Definition

    An IIFE is a JavaScript function that runs as soon as it is defined, without needing to be called separately.

    Why Do We Need IIFE ?

    Before modern JavaScript features like let, const, and modules, developers faced problems such as:

    • Global variable pollution

    • Variable name conflicts

    • Unwanted access to variables

    IIFE solves these problems by creating a private scope.

    Syntax of IIFE

    Basic Syntax

    (function () {

      // code to execute immediately

    })();

    Alternate Syntax

    (function () {

      console.log("IIFE executed");

    }());

    Both syntaxes are valid.

    Important Syntax Rule

    The function must be wrapped in parentheses.

    Reason:

    • JavaScript treats function() as a declaration

    • Parentheses convert it into an expression

    • Only expressions can be immediately invoked

Immediately Invoked Function Expression (IIFE)

Executes a function immediately after it is defined.

// IIFE example

(function () {
  console.log("Hello from IIFE");
})();
  • The function runs immediately without being called.

IIFE with Parameters and Return

Runs instantly with arguments and can return a value.

// IIFE with parameter

(function (name) {
  console.log("Welcome " + name);
})("Rahul");


// IIFE with return value

let result = (function () {
  return 10 + 20;
})();

console.log(result); // 30
  • Scope in IIFE

IIFE Private Scope

Keeps variables hidden inside the function and prevents outside access.

// Variables inside IIFE are private

(function () {
  let message = "Private Variable";
  console.log(message); // accessible inside
})();

console.log(message); // Error (not accessible outside)
  • The variable message cannot be accessed outside.

IIFE vs Normal Function

Compares reusable functions with one-time execution and scope isolation.

// Normal Function

function show() {
  console.log("Normal Function");
}

show();


// IIFE (runs immediately)

(function () {
  console.log("IIFE Function");
})();
  • Analogy

    Think of IIFE like:

    • A disposable cup

    • Use once and throw away

    It serves a purpose and then disappears.

    Use Cases of IIFE

Practical Uses of IIFE

Applies IIFE for privacy, initialization, and modular code structure.

// 1. Avoid Global Scope Pollution

(function () {
  let counter = 0;
  counter++;
  console.log(counter);
})();


// 2. Initialization Code

(function () {
  console.log("App Initialized");
})();


// 3. Data Privacy

let user = (function () {
  let password = "secret123";

  return {
    getPassword: function () {
      return password;
    }
  };
})();

console.log(user.getPassword());


// 4. Module Pattern

let calculator = (function () {
  function add(a, b) {
    return a + b;
  }

  return {
    add: add
  };
})();

console.log(calculator.add(5, 3));
  • IIFE with Arrow Function (Modern JavaScript)

Arrow Function IIFE

Executes an arrow function instantly without naming it.

// Arrow IIFE

(() => {
  console.log("Arrow IIFE");
})();
  • Multiple IIFEs in One File

Multiple IIFEs Usage

Runs multiple isolated functions independently in the same file.

// Multiple IIFEs

(function () {
  console.log("First IIFE");
})();

(function () {
  console.log("Second IIFE");
})();
  • They do not interfere with each other.

    Common Mistakes

    • Forgetting parentheses

    • Trying to call IIFE again

    • Expecting variables to be accessible outside

    • Overusing IIFE unnecessarily

    When Should You Use IIFE ?

    • One-time execution logic

    • Creating private scope

    • Initialization code

    • Avoiding global variables

    When NOT to Use IIFE ?

    • When functions need to be reused

    • When ES6 modules are available

    • When code readability suffers

    IIFE in Modern JavaScript

    With let, const, and modules:

    • IIFE usage has reduced

    • But still important to understand

    • Found in legacy code and interviews