LESSON 08 / 16·2 min readFoundation

Closures

Try code in the playground
01 Understand02 Recall03 Prepare

Understand the concept

A closure is a function together with access to the variables in the scope where it was created. That access remains available even after the outer function has finished running. Closures are useful for private state, callbacks and functions configured with some remembered value.

Important ideas

  • A function keeps access to variables from where it was created.

  • Example: a counter function remembers its count between calls.

  • Closures can also keep large objects in memory longer than needed.

  • A closure keeps access to bindings, not a frozen snapshot; later changes to those bindings can be visible.

  • Each call to a function factory can create a separate set of remembered variables.

  • Long-lived callbacks can retain data through closures, so remove them when they are no longer needed.

Work through the example

JavaScript
function createCounter() {
  let count = 0;
  return function increment() {
    count += 1;
    return count;
  };
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
  • createCounter has returned, but increment still has access to its count.
  • Calling createCounter() again creates a separate counter with its own state.
PAUSE & RECALL

Can you explain it without the notes?

What is a closure?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

A closure is a function together with access to the variables in the scope where it was created. That access remains available even after the outer function has finished running. Closures are useful for private state, callbacks and functions configured with some remembered value.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Explain a counter or callback example and mention that remembering state can be useful but also retain memory.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: How does this work? How are arrow functions different?

Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “What is a closure?”. Examples are study fragments; framework behavior can depend on your version.