⚡ JavaScript Functions Deep Dive #3: Understanding IIFE (Immediately Invoked Function Expressions)

pushpesh kumarpushpesh kumar
3 min read

JavaScript is full of surprises — and one of its cleverest patterns is the Immediately Invoked Function Expression (IIFE). If you’ve ever seen a function that executes as soon as it’s defined, you’ve seen an IIFE in action.

In this post, we’ll demystify:

  • What an IIFE is

  • Why it exists

  • How it works

  • When and where to use it


🧠 What Is an IIFE?

An Immediately Invoked Function Expression (IIFE) is a function that runs immediately after it is defined.

🔸 Syntax:

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

✅ Output: "I ran immediately!"


✅ IIFE Breakdown

ConceptExplanation
Function ExpressionWrapped in () to treat it as a value
Immediately InvokedFollowed by () to execute it right away
Private ScopeCreates a new execution context — variables inside won’t leak out

🔍 Why Do We Need IIFEs?

Before ES6 introduced let and const (which support block scope), JavaScript only had function scope. IIFEs gave developers a way to create isolated scopes to:

  • Avoid polluting the global namespace

  • Encapsulate private variables

  • Avoid conflicts between scripts


🧪 Example: Using IIFE for Isolation

var user = "global";

(function () {
  var user = "scoped";
  console.log(user); // "scoped"
})();

console.log(user); // "global"

💡 The variable user inside the IIFE does not affect the global user. Also we did not need to create a named function declaration and make an explicit function call.


🧰 Use Cases for IIFEs

Use CaseDescription
Scope isolationAvoid variable collisions in global scope
Module patternUsed in early JS to create private data
One-time setupInitialization code that runs once (e.g., configs, caching)
Loop variable captureUsed with var loops to preserve variable values in async callbacks

🧪 IIFE in a for Loop (Pre-ES6)

for (var i = 0; i < 3; i++) {
  (function (j) {
    setTimeout(() => console.log(j), 100);
  })(i);
}
// Output: 0 1 2

Without the IIFE, you'd get 3 3 3 because var is not block-scoped.


🧑‍💻 Variations of IIFE Syntax

FormSyntaxNotes
Classic(function() { ... })();Most common
Arrow(() => { ... })();Works like regular IIFE
With parameters(function(name) { ... })("Alice");Pass arguments directly

Example with parameters:

(function(name) {
  console.log(`Hello, ${name}`);
})("Pushpesh");

🚫 When Not to Use IIFEs

  • When you're using let and const — modern block scoping often makes IIFEs unnecessary.

  • When you need reusable logic (IIFEs run once).

  • When readability is more important than cleverness.


✅ Recap

FeatureIIFE
✅ Runs immediatelyYes
✅ Creates private scopeYes
🧠 Useful before ES6Very
✅ Still used in tooling/modulesYes
❌ Good for multiple usesNo (runs only once)
0
Subscribe to my newsletter

Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

pushpesh kumar
pushpesh kumar