Skip to content
FunctionsChapter 16 / 47Intermediate5 min read

Closures

What JavaScript closures are, how an inner function remembers outer variables, and how they are used in counters, private data and factories.

On this page

1. What are closures?

In JavaScript, whenever a function is created inside another function, it carries a reference to the variables around it. This "backpack" is the closure.

A closure is not a special syntax. Every function creates one, but the difference only shows when the inner function is returned outside and runs later.

2. Why does it matter?

Without closures, keeping data private and remembering state between function calls is hard. Global variables are dangerous for that job.

State with a global variableState with a closure
Any file can change the valueOnly the inner functions can change it
Risk of name collisionsEvery instance has its own private data
Two counters share one valueEach counter keeps its own value
Hard to testState is encapsulated and predictable

3. Where is it used?

AreaWhat the closure does
Counters and statecreateCounter() remembers the count of each call
Private dataData like a bank balance cannot be changed directly from outside
Function factoriesMaking a double function with makeMultiplier(2)
Event handlersThe handler remembers its own id on click
Debounce / throttleRemembering the timer id between calls
React hooksuseState and handlers run on closures

4. How does it work?

A closure stands on lexical scope. The variables of the place where a function was written become part of its scope chain.

How a closure is formed
The outer function runs and creates a variable
An inner function is created inside
The outer function returns the inner function
The outer function ends, but the variable stays alive
The inner function keeps using that variable later

An important point: a closure keeps a live reference, not a copy, of the variable. If the variable changes, the closure sees the new value.

5. Code example

Counter with private state

js
function createCounter(start = 0) {
  let count = start;

  return {
    increment: () => ++count,
    decrement: () => --count,
    value: () => count,
  };
}

const a = createCounter();
const b = createCounter(10);

a.increment();
a.increment();
b.decrement();

console.log(a.value());
console.log(b.value());
console.log(a.count);

Function factory

js
function makeMultiplier(factor) {
  return (n) => n * factor;
}

const double = makeMultiplier(2);
const triple = makeMultiplier(3);

console.log(double(5));
console.log(triple(5));

How does the code work?

ItemMeaning
let countA private variable inside createCounter
Returned methodsAll three arrow functions remember count through the closure
a and bEach call has its own separate count, so 2 and 9
a.countundefined, because count is not accessible from outside
makeMultiplier(2)A new function that remembers factor = 2
Output10 and 15

Interview tip

The classic question: in a var loop, why does setTimeout print the last value every time? Because all the callbacks share the closure of one var i. let creates a new binding for each iteration, so each callback has its own value.

6. Common mistakes

Mistake: Thinking a closure is a copy of the value

Why? A closure keeps a live reference, so if the variable changes later, the closure sees the new value too.

Better: If you need to fix the value at that moment, pass it into a new const or a function parameter.

Mistake: Callbacks in a loop with var

Why? All the callbacks share one variable, and the last value is printed.

Better: Use let in the loop so that each iteration has its own binding.

Mistake: Holding big things in a closure for no reason

Why? As long as the closure is alive, the objects it references are not garbage collected, and memory keeps growing.

Better: Capture only the data you need, and remove or clear event listeners and timers when their job is done.

Mistake: Old state in a React handler (stale closure)

Why? The handler captured the value from the previous render, so it does not see the new state.

Better: Use an updater function, like setCount(c => c + 1), and keep the effect dependencies correct.

7. What to learn before and after

Suggested order
Scope & Hoisting
Closures
Higher-Order Functions
Debounce & Throttle

Final quick revision

PointDetail
ClosureA function + its lexical environment
When it formsWhenever a function is created, it shows when it runs later
Reference or copyA live reference
BenefitPrivate state, factories, handlers
RiskStale values and memory leaks