IIFE (Immediately Invoked Function Expressions)
Introduction
An IIFE is a function expression that is invoked immediately after it is created: (function () { ... })().
Before ES modules and block-scoped let/const, IIFEs were the standard way to create private scope, avoid accidental globals, and capture loop values. They still appear in legacy code, build output, bookmarklets, and occasional scripts that need a one-time private setup.
Why This Matters
IIFEs connect several core ideas at once: expressions, function scope, closures, private state, and historical JavaScript module patterns. Interviewers also use them to fix the classic var loop callback bug.
Theory
Why the parentheses?
function () {} by itself is parsed as a declaration in many positions, and declarations require names. Wrapping it in parentheses forces JavaScript to treat it as an expression, which can then be invoked immediately. Common forms are (function () { ... })(), (function () { ... }()), and (() => { ... })().
A function call creates a new scope. Variables declared inside the IIFE are not visible outside. This prevents temporary setup names from leaking into the surrounding scope. An IIFE can also return functions or objects that close over private variables. The outside world can use the returned API but cannot directly access the hidden state.
ES modules, let, const, and block scope replaced many IIFE use cases. Still, understanding IIFEs helps you read older code and explain how closures can create privacy without classes or private fields.
Visual Diagrams
outer scope appName counterApi -> returned object IIFE scope private count helper functions outside can call counterApi.next() outside cannot read count directly
The IIFE runs once, then its local variables survive only if returned functions close over them.
Code Examples
Isolate setup variables
The temporary variables disappear after the IIFE finishes, keeping the outer scope clean.
Create private state
Only the returned methods can access count. This is the classic closure-based module pattern.
Playground
Press Run to execute the code and see output here.
Output Prediction
Predict the output #1
1var value = 'global';2 3(function () {4 var value = 'iife';5 console.log(value);6})();7 8console.log(value);Predict the output #2
1for (var i = 0; i < 3; i++) {2 (function (copy) {3 setTimeout(function () {4 console.log(copy);5 }, 0);6 })(i);7}Coding Exercises
Build a private ID generator
MediumUse an IIFE to create nextOrderId. The returned function should keep a private counter starting at 1 and return IDs like ORD-1, ORD-2, and ORD-3. The counter must not be directly accessible from outside.
Interview Questions
1What problem did IIFEs solve before ES modules and `let`?
They created a private function scope immediately, preventing temporary variables from leaking into the global scope. They also enabled closure-based module patterns and captured loop values for var callbacks. Modern modules and block scope reduce the need, but IIFEs remain important for reading legacy JavaScript.
Follow-ups
- Why are parentheses needed around the function?
- How does an IIFE fix the `var` loop closure bug?
2How can an IIFE create private state?
The IIFE runs once, creates local variables, and returns functions that close over those variables. The returned functions can read or update the hidden state later, but outside code has no direct reference to the local bindings.
Quiz
1. What is the primary purpose of an IIFE?
Summary
- An IIFE is a function expression called immediately after creation.
- Parentheses force the function into expression position so it can be invoked.
- IIFEs isolate temporary variables and can create closure-based private state.
- Modern modules and block scope reduce IIFE usage, but legacy and interview code still rely on them.
Cheat Sheet
Forms: (function () { ... })() and (() => { ... })().
Why: create a scope immediately, avoid globals, hide setup variables, capture var loop values.
Private state: return functions that close over IIFE locals.
Modern replacement: ES modules, let, const, block scope, private class fields.