An Immediately Invoked Function Expression (IIFE) is a JavaScript function that runs as soon as it is defined. It is a popular design pattern used to manage scope and avoid polluting the global namespace.

1. The Syntax

An IIFE is defined by wrapping a function in parentheses and then immediately calling it with another set of parentheses.

JavaScript

(function () {
  // Logic goes here
  console.log("I run immediately!");
})();

Why the extra parentheses?

  1. The Grouping Operator (…): JavaScript sees the keyword function at the start of a line as a declaration. Declarations require a name. By wrapping it in parentheses, you tell the engine to treat it as an expression instead.
  2. The Invocation (): The second set of parentheses at the end tells JavaScript to execute the function immediately.

2. Passing Arguments

Just like regular functions, you can pass data into an IIFE. This is often used to alias global variables (like window or jQuery) to make them shorter or more secure within the function’s scope.

JavaScript

(function (name, year) {
  console.log(`Hello ${name}, welcome to ${year}!`);
})("User", 2026); 

// Output: Hello User, welcome to 2026!

3. Why Use an IIFE?

A. Avoiding Global Scope Pollution

In older JavaScript (before let and const), variables declared with var were function-scoped. If you wrote code in a script file, those variables became “global,” which could lead to naming collisions with other scripts.

JavaScript

// Without IIFE
var score = 10; // This is now a global variable

// With IIFE
(function() {
  var privateScore = 10; // This is hidden inside this function
})();

console.log(privateScore); // ReferenceError: privateScore is not defined

B. Creating Private State

IIFEs are often used in conjunction with Closures (as we discussed previously) to create private variables that can only be accessed by certain methods.

JavaScript

const counter = (function() {
  let count = 0; // Private variable

  return {
    increment: function() {
      return ++count;
    }
  };
})();

console.log(counter.increment()); // 1
console.log(counter.increment()); // 2

4. Modern Alternative: Block Scope

Since the introduction of ES6 (let and const), the need for IIFEs has decreased. You can now create a private scope simply by using a set of curly braces:

JavaScript

{
  let privateVar = "I am hidden";
  const alsoHidden = "Me too";
}
// privateVar is not accessible here

However, IIFEs are still widely used in:

  • Legacy codebases.
  • Minifying code (to shorten variable names locally).
  • Top-level await patterns in certain environments.
  • Modular patterns where you want to export an object immediately.

Categorized in:

Javascript,