Closures in JavaScript

Introduction

A closure is when a function remembers variables from the scope where it was created—even after that outer function has finished. Closures power private state, factories, and callbacks. They are one of the most important ideas in JavaScript for intermediate developers.

Prerequisites

Inner Function Sees Outer Variables

inner closes over message.

Counter with Private State

count is not exported—only methods access it.

Closures in Loops (Historical Pitfall)

With var, every timeout shared one i. With let, each iteration gets its own binding:

javascript
// let creates per-iteration binding
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 10 * i);
}

Function Returning Function

javascript
// multiplyBy returns specialized multiplier
function multiplyBy(factor) {
  return (n) => n * factor;
}
 
const double = multiplyBy(2);
const triple = multiplyBy(3);
 
console.log(double(5));
console.log(triple(5));

Memory Note

Closures keep outer variables alive while the inner function is reachable—avoid accidental retention of huge objects in long-lived callbacks.

Mini Example: Rate Limiter Stub

FAQ

Is closure a special syntax?

No—it is behavior: inner function + referenced outer variables.

Can closures cause bugs?

Yes—stale values in async code or memory leaks if closures hold large graphs.

Same as scope chain?

Related—closure is the practical effect of lexical scope plus live bindings.

What comes next?

Callbacks and higher-order functions.