Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript IIFE

An IIFE is a function expression that runs immediately after it is defined.

It creates a private scope and avoids leaking variables globally.

Why We Need It

IIFEs were a popular way to isolate variables before ES modules.

They are still useful in quick scripts and legacy codebases.

Syntax

(function() { ... })()
(() => { ... })()

Basic Example

1. Basic IIFE

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

The function executes immediately after definition.

Real World Example

2. IIFE with arguments

(function(name) {
  console.log("Hello " + name);
})("Ava");

Pass arguments into the IIFE like a normal function.

Multiple Use Cases

Run Immediately

An IIFE runs as soon as it is defined.

It is useful for creating a private scope.

Avoid Global Pollution

IIFEs help avoid polluting the global namespace.

This was especially common before ES modules.

Modern Alternatives

With ES modules, IIFEs are less common but still useful in quick scripts.

They remain a good tool to understand legacy code.

More Examples

3. Arrow IIFE

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

IIFEs can be written with arrow syntax as well.

4. Private scope

const value = "global";

(function() {
  const value = "local";
  console.log(value);
})();

console.log(value);

IIFE creates a private scope.

Comparison

Without

var counter = 0;
// counter is global

With

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

Common Mistakes and Fixes

Forgetting parentheses

Wrap the function to make it an expression.

Overusing IIFEs

Prefer modules for larger codebases.

Hard-to-read nesting

Keep IIFEs short and focused.

Interview Questions

What is an IIFE?

A function that runs immediately after it is defined.

Why use an IIFE?

To create a private scope and avoid globals.

Is IIFE still relevant?

Yes, especially in scripts or legacy code.

Practice Problem

Practice: Write an IIFE that logs the sum of two numbers.

// TODO: IIFE that logs 5 + 7

One Possible Solution

(function(a, b) {
  console.log(a + b);
})(5, 7);

Frequently Asked Questions

What does IIFE mean?

Immediately Invoked Function Expression.

Why use an IIFE?

To run code immediately and create a private scope.

Are IIFEs still used today?

Less common with ES modules, but still useful in scripts.

Try It Yourself

Try passing different values into the IIFE.