JavaScriptInterview preparation
Foundation·Concept·2 min read

What is a closure?

Practice this question

Definition:

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.

Key points:

  • 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.

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.

Interview point:

  • Explain a counter or callback example and mention that remembering state can be useful but also retain memory.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “What is a closure?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.