Skip to content
Rajat Kumar
Go back

Immediately-Invoked Function Expression (IIFE)

While working on JS module bundling at Netflix, I noticed IIFEs are a recurring pattern in JavaScript modules. Many developers find them challenging to understand, so let’s break it down.

Table of contents

Open Table of contents

What Exactly Is an IIFE?

IIFE (pronounced “iffy”) stands for Immediately-Invoked Function Expression. It’s a way to execute functions immediately, as soon as they are created.

(function () {
  /* Simple IIFE! */
})();

Let’s break down the syntax:

// function definition inside parentheses
(function () {
  /* Simple IIFE! */
})(); // <-- invoke that function here

The wrapping parentheses around the function definition tell the parser to treat this as an expression rather than a declaration. The trailing () then executes that expression immediately.

Why Do We Need IIFEs?

In JavaScript, whenever we invoke a function, we create a new execution context. Any variable (or even new functions) defined within an invoked function can only be accessed inside—and never from outside—that context.

This means invoking a function gives us a way to create something that resembles private variables.

IIFE allows us to define an isolated scope and execute code in this scope.

Can IIFEs Return Something?

Yes! IIFEs can return objects, functions… anything.

var counter = (function () {
  var i = 0;

  return {
    get: function () {
      return i;
    },
    set: function (val) {
      i = val;
    },
    increment: function () {
      return ++i;
    },
  };
})();

counter.get(); // 0
counter.set(3);
counter.increment(); // 4
counter.increment(); // 5

counter.i; // undefined
i; // ReferenceError: i is not defined

The IIFE returns an object that exposes specific methods while keeping the variable i completely private. You can’t access i directly—only through the methods we chose to expose.

The Module Pattern

A module is reusable, self-contained code that:

The counter example above demonstrates the Module Pattern. With very little code, we managed to:

  1. ✅ Namespace related methods and properties
  2. ✅ Minimize global scope pollution
  3. ✅ Create private variables

This is the power of IIFEs. Before ES6 modules became standard, this pattern was the way to write modular JavaScript.


Even with modern ES6 modules, understanding IIFEs helps you read legacy code and understand how bundlers work under the hood. 🧠


Share this post on:

Previous Post
Git - Delete Your Local Branches