Guides/Closures Explained Step by Step

Closures Explained Step by Step

Functions remember the environment where they were created — including the interview trap with var and timers.

Rajan Pandey · About the author

Rajan Pandey is a Full Stack AI Engineer with nearly 3 years of professional experience building production-ready web applications, SaaS platforms, and developer-focused tools. He specializes in JavaScript, TypeScript, React.js, Next.js, Node.js, and the MERN stack.He has worked on 15+ production applications across SaaS, EdTech, and GenAI products, with experience spanning frontend architecture, backend development, REST APIs, database design, authentication, and third-party integrations. StackTools was created as a way to make everyday development tasks simpler and JavaScript concepts easier to understand through interactive, browser- based tools.His goal is to build practical utilities that developers can use without unnecessary complexity, registration, or uploading their data to external servers.

What a closure is

A closure is a function bundled with references to variables from its outer lexical scopes. Those bindings outlive the outer function call if the inner function escapes (returned, stored, or passed to setTimeout).

function makeCounter() {
  let n = 0;
  return function inc() {
    n += 1;
    return n;
  };
}
const c = makeCounter();
console.log(c()); // 1
console.log(c()); // 2
Open in Visualizer

n is not copied into inc; both calls mutate the same binding. That distinction — binding vs snapshot — explains the timer bug below.

The for + var + setTimeout bug

var is function-scoped. The loop reuses one i. Each timeout callback closes over that same binding. By the time macrotasks run, the loop finished and i is 3:

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// prints 3 3 3
Open in Visualizer

Fixes: let, IIFE, forEach

let in a for head creates a new binding per iteration:

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// prints 0 1 2
Open in Visualizer

Pre-let code used an IIFE to capture the value:

for (var i = 0; i < 3; i++) {
  (function (j) {
    setTimeout(() => console.log(j), 0);
  })(i);
}
// prints 0 1 2
Open in Visualizer

Practical pattern: private state

Modules and factory functions use closures for encapsulation without classes. Prefer that when the API is a small set of functions sharing state. Avoid nesting closures deeply just to hide a single boolean — readability suffers and accidental retention of large objects becomes harder to spot.

When not to force closures

If you only need a value later, pass it as an argument. If you need many instances with methods, a class or explicit object may communicate lifetime better. Closures are a tool for lexical capture — not a substitute for clear data flow.

Try it live

Open the matching StackTools utility — runs in your browser.

Open JS Execution Visualizer