sr✳SHUBHAM RAJFRONTEND ENGINEER
FULL TECHNICAL GUIDEFoundation3 min read

What does a JavaScript closure retain?

Closures explain how functions continue to access lexical bindings after their outer scope has returned.

JavaScript#scope#functions
THE ANSWER / PLAIN ENGLISH

The idea to remember.

A closure is a function together with access to the lexical environment in which it was created. The function can continue reading and updating those bindings after the outer function has returned. A closure does not automatically freeze an immutable snapshot of every value.

From first example to real project.

Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.

Basic: closure remembers a binding

01 / BEGINNER

The returned function can still use a variable from its outer scope.

JAVASCRIPT / EXAMPLE
function createCounter() {
  let count = 0;
  return () => ++count;
}
const next = createCounter();
console.log(next()); // 1
console.log(next()); // 2

Intermediate: block scope

02 / INTERMEDIATE

Each iteration can keep its own binding with let.

JAVASCRIPT / EXAMPLE
const callbacks = [];
for (let i = 0; i < 3; i++) callbacks.push(() => i);
console.log(callbacks.map(fn => fn())); // [0, 1, 2]

Real scenario: isolate private state

03 / REAL SCENARIO

A factory can retain private data without exposing it globally.

JAVASCRIPT / EXAMPLE
function createCart() {
  const items = [];
  return {
    add: item => items.push(item),
    total: () => items.reduce((sum, item) => sum + item.price, 0)
  };
}

Try it in your own words.

Explain what does a JavaScript closure retain without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.

Keep learning here.

Explore more in-depth guides, exercises and related interview questions in this library.

Browse JavaScript study guides ↗
← Back to question library

Have something
in mind?

Start a conversation