JavaScript IIFE

An IIFE is a function that runs the moment JavaScript reads it — no need to call it separately. The name says it all: Immediately Invoked means it runs right away, and Function Expression means it is a function defined as a value, not a declaration.

What Does an IIFE Look Like?

(function() {
  console.log("I run immediately!");
})();

Two things make this work:

  1. The function is wrapped in parentheses ( ) — this turns it into an expression.
  2. The () at the end calls it right away.

Diagram: IIFE Anatomy

  (  function() {          }  )  ()
  │  └────────────────────┘  │  │
  │     The function body    │  │
  │                          │  │
  └── wraps it as expression ┘  │
                                │
                     calls it immediately

Why Use an IIFE?

JavaScript variables declared with var leak into the global scope. This means any part of the page can accidentally overwrite them. An IIFE creates a private bubble — everything inside stays inside.

Problem Without IIFE

var count = 10;      // global — anyone can change this

function changeCount() {
  count = 99;        // oops, overwrote the global count
}
changeCount();
console.log(count);  // 99

Solved With IIFE

(function() {
  var count = 10;    // stays inside the IIFE
  console.log(count); // 10
})();

console.log(typeof count); // "undefined" — not accessible outside

Diagram: IIFE Scope Bubble

Global Scope
┌──────────────────────────────────┐
│                                  │
│   IIFE Scope (private bubble)    │
│  ┌────────────────────────────┐  │
│  │  var count = 10            │  │
│  │  (safe inside here)        │  │
│  └────────────────────────────┘  │
│                                  │
│   count is NOT visible here      │
└──────────────────────────────────┘

IIFE with Arrow Function

Modern JavaScript lets you write IIFEs with arrow functions for shorter syntax.

(() => {
  console.log("Arrow IIFE runs!");
})();

IIFE with Parameters

You can pass values into an IIFE just like a regular function call.

(function(name, age) {
  console.log(name + " is " + age + " years old.");
})("Priya", 25);

// Output: Priya is 25 years old.

The values "Priya" and 25 go into the () at the end — they become the parameters name and age.

IIFE with a Return Value

An IIFE can return a value and store it in a variable.

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

console.log(result); // 30

Diagram: IIFE Returning a Value

(function(a, b) { return a + b; })(10, 20)
          │                       │
          │   a = 10, b = 20      │
          │   returns 30          │
          ▼                       │
   result = 30 ◄──────────────────┘

Real-World Use: Module Pattern

Before ES6 modules existed, developers used IIFEs to create module-like structures — private data with a public interface.

let counter = (function() {
  let count = 0; // private

  return {
    increment: function() { count++; },
    decrement: function() { count--; },
    getCount:  function() { return count; }
  };
})();

counter.increment();
counter.increment();
counter.increment();
console.log(counter.getCount()); // 3
console.log(counter.count);      // undefined — private!

Diagram: IIFE Module Pattern

┌──────────────────────────────────────┐
│  IIFE runs once, returns an object   │
│                                      │
│  Private:  count = 0                 │
│                                      │
│  Public methods returned:            │
│  ┌─────────────────────────────┐     │
│  │  increment()  decrement()   │     │
│  │  getCount()                 │     │
│  └─────────────────────────────┘     │
│                                      │
│  count is never directly reachable   │
└──────────────────────────────────────┘

IIFE for Initialization Code

IIFEs are perfect for setup code that runs once when a page loads — like setting up event listeners or fetching initial data.

(function() {
  // Runs once on page load
  document.title = "Welcome to My App";
  console.log("App initialized");
})();

Named IIFE

You can give an IIFE a name for easier debugging. The name is only visible inside the function itself.

(function setup() {
  console.log("Setup complete");
})();

// setup() called here would throw an error — not accessible outside

IIFE vs Regular Function

FeatureRegular FunctionIIFE
When it runsWhen you call itImmediately, once
Can be called againYesNo
Creates private scopeYes (if nested)Yes (by design)
Common useReusable logicOne-time setup, module pattern

When to Use an IIFE Today

With modern JavaScript (ES6+), let and const already have block scope, and ES modules handle private code cleanly. But IIFEs still appear in:

  • Legacy code that uses var.
  • Scripts that run in environments without module support.
  • Situations where you need code to run once without creating global names.
  • Older library patterns like jQuery plugins.

Summary

An IIFE is a function that defines and calls itself at the same time. It creates a private scope that protects variables from polluting the global space. IIFEs power the classic module pattern and still appear in legacy JavaScript. Understanding them is key to reading older codebases and understanding how JavaScript scope works at a deeper level.

Leave a Comment

Your email address will not be published. Required fields are marked *