What Is a Closure in JavaScript? Explained With Examples

A closure is a function that remembers the variables from its outer scope even after that scope has finished executing. Learn how and why with examples.

Published September 16, 2026

A closure is created when a function is defined inside another function and continues to have access to the outer function's variables even after the outer function has returned. The inner function 'closes over' those variables.

Common causes

  • JavaScript functions form a lexical scope chain at creation time, not at call time
  • Inner functions keep a live reference to their enclosing scope's variables rather than copying their values

How to fix it

  • Use closures deliberately for data privacy — variables inside the outer function aren't accessible from outside it
  • Use closures to create factory functions and counters that keep their own private state
  • Watch for closures capturing a loop variable by reference — declare with let instead of var to get a fresh binding per iteration

Example

function makeCounter() {
  let count = 0
  return function () {
    count++
    return count
  }
}

const counter = makeCounter()
counter() // 1
counter() // 2

FAQ

Why do closures matter in loops?

With var, all iterations of a loop share the same variable, so callbacks created inside the loop all see its final value. With let, each iteration gets its own binding, so each closure captures the value at that iteration.

Do closures cause memory leaks?

A closure keeps its outer variables alive as long as the closure itself is reachable. This is normal, but holding onto large objects in a long-lived closure (like an event listener) can prevent them from being garbage collected.

More JavaScript articles