Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

JavaScript Closures: Lexical Scope, Practical Examples and Pitfalls

Why can a function still read variables from a factory that has already returned? Why do callbacks created in a loop sometimes return the same number? Closures explain both behaviors. They underpin function factories, event subscriptions and React patterns. Understanding them makes it possible to predict behavior rather than guess at fixes.

Published Written by Reading time 7 min read
On this page Contents: quick navigation between sections

What is a closure and lexical scope?

function createLabelReader(initialLabel) {
  let label = initialLabel;

  function read() {
    return label;
  }

  function update(nextLabel) {
    label = nextLabel;
  }

  return { read, update };
}

const reader = createLabelReader("Draft");

console.log(reader.read()); // Draft

reader.update("Published");

console.log(reader.read()); // Published

Lexical scope follows where a function is written, not where it is called. A closure gives a function access to bindings in its surrounding environment. Returning the function does not remove that access after the enclosing call finishes. [1][2]

The example's read and update functions refer to the same label binding. After the update, reading it returns Published rather than Draft. This is not a copy of the value at function creation. A lexical environment is a specification concept, not a guarantee of a particular engine memory layout.

Private state and independent factory calls

function createCounter(initialValue = 0) {
  let count = initialValue;

  return {
    increment() {
      count += 1;

      return count;
    },
    getValue() {
      return count;
    },
  };
}

const firstCounter = createCounter();
const secondCounter = createCounter(10);

console.log(firstCounter.increment()); // 1
console.log(secondCounter.increment()); // 11
console.log(firstCounter.getValue()); // 1

Each createCounter call establishes its own count binding. The two methods from one call share that binding, while methods from another call use a different environment. [1][2]

External callers cannot directly assign to the local count variable. The returned API can control access and enforce invariants. This is encapsulation, not a security boundary against other code running in the same environment. For many instances, compare the pattern with classes and private # fields rather than assuming one is universally faster.

Why var and let behave differently in loops

const sharedCallbacks = [];
const separateCallbacks = [];

for (var index = 0; index < 3; index += 1) {
  sharedCallbacks.push(() => index);
}

for (let index = 0; index < 3; index += 1) {
  separateCallbacks.push(() => index);
}

console.log(sharedCallbacks.map((read) => read())); // [3, 3, 3]
console.log(separateCallbacks.map((read) => read())); // [0, 1, 2]

A var declaration in a loop has one binding shared by its callbacks. A classic for loop with let in its initializer creates a separate binding per iteration. The first group therefore returns 3, 3, 3 after the loop, while the second returns 0, 1, 2. [1][3]

A timer is unnecessary to demonstrate this issue; invoking the callbacks after the loop is enough. Merely replacing var with let outside the loop does not solve it, because there would still be one shared binding. When iterating over collections, for...of with const is also a readable option.

Function factories in practice: price formatting

function createPriceFormatter(locale, currency) {
  const formatter = new Intl.NumberFormat(locale, {
    style: "currency",
    currency,
  });

  return function formatPrice(amount) {
    if (!Number.isFinite(amount)) {
      throw new TypeError("Expected a finite amount");
    }

    return formatter.format(amount);
  };
}

const formatPrice = createPriceFormatter("en-US", "USD");

console.log(formatPrice(12.5)); // $12.50
console.log(formatPrice(100)); // $100.00

A closure can retain configuration or a service object so callers need not repeatedly supply the same arguments. A factory returns a function with a narrower contract and keeps its configuration inside. [1]

createPriceFormatter initializes one Intl.NumberFormat for the selected locale and currency. Its returned function validates that the amount is finite and reuses the formatter. This is not a financial arithmetic system: monetary representation and rounding rules require separate decisions. Create a new formatter if the locale or currency changes.

Live bindings versus value snapshots

let activeFilter = "all";

function createFilterReaders() {
  const savedFilter = activeFilter;

  return {
    readCurrent() {
      return activeFilter;
    },
    readSaved() {
      return savedFilter;
    },
  };
}

const readers = createFilterReaders();

activeFilter = "open";

queueMicrotask(() => {
  console.log(readers.readCurrent()); // open
  console.log(readers.readSaved()); // all
});

A closure reads its referenced binding when the function executes. You can intentionally preserve an earlier value in a separate variable. Here the microtask runs after the synchronous filter update, so readCurrent returns open and readSaved returns all. [1][2]

This matters in asynchronous flows: a request may need to remember the parameters it started with, while the UI must compare the response against the current filter before rendering. Assigning an object to const is not a deep copy; mutations can still be seen through other references. The example's snapshot works because the filter is a string.

Stale closures in React

import { useEffect, useState } from "react";

export function ElapsedSeconds() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setSeconds((previousSeconds) => previousSeconds + 1);
    }, 1000);

    return () => {
      clearInterval(intervalId);
    };
  }, []);

  return <output>{seconds} s</output>;
}

Each React render has its own snapshot of props and state. A callback created during a previous render can therefore read an older value. An interval in an effect with empty dependencies that calls setSeconds(seconds + 1) reads the state from the render that created that effect. [4][5][9]

The corrected version uses a functional updater, which receives the previous value from React's update queue. It need not depend on seconds just to increment it. Cleanup clears the timer. If an effect reads other reactive values, declare the corresponding dependencies instead of disabling the linter. This example counts timer callbacks, not precise wall-clock time, because timers may be delayed.

Closures, subscriptions and memory leaks

function subscribeToUpdates(target, onUpdate) {
  const controller = new AbortController();

  function handleUpdate(event) {
    onUpdate(event.detail);
  }

  target.addEventListener("update", handleUpdate, {
    signal: controller.signal,
  });

  return function unsubscribe() {
    controller.abort();
  };
}

const target = new EventTarget();
const unsubscribe = subscribeToUpdates(target, console.log);

target.dispatchEvent(new CustomEvent("update", { detail: 42 }));
// 42

unsubscribe();

target.dispatchEvent(new CustomEvent("update", { detail: 99 }));
// No output

A reachable function can keep data it needs alive. If a long-lived target retains a listener that references a model or DOM element, that data may remain reachable even after its view closes. A closure is not inherently a leak. [6][7][8]

subscribeToUpdates returns an explicit unsubscribe function that removes the listener through AbortController. The second event no longer invokes the callback. Release unused references to the subscription handle too. In Chrome DevTools, compare heap snapshots after repeated view mounts and unmounts, then inspect Retainers to identify retaining paths. Heap growth alone is not proof of a leak; it may reflect caching or temporary allocation.

A closure preserves access to lexical bindings, not an automatic copy of every value. Separate factory calls provide independent state, while functions from one call can share it. Choose intentionally between reading live values and preserving snapshots, and give long-lived subscriptions explicit cleanup. Closures are useful when their lifetime and responsibilities are clear.

JavaScript Closures Lexical Scope Scope React Memory Management Callbacks Event Listeners

Frequently asked questions

Does a closure copy a variable's value?

No. It can access the lexical binding. A separate variable can preserve an earlier value, but object references require special care. [1][2]

Why do callbacks in a var loop return the same value?

They share one variable binding. A let declaration in the for initializer creates distinct per-iteration bindings. [1][3]

How do you fix a stale closure in React?

Use a functional updater when computing state from previous state. For effects that synchronize external systems, declare the reactive dependencies the effect actually reads. [4][5]

Do closures cause memory leaks?

Not automatically. A leak occurs when data that is no longer needed remains reachable through long-lived functions, listeners, timers or other references. [7][8]

Sources and references

  1. MDN, Closures↩1↩2↩3↩4↩5↩6↩7↩8↩9↩10↩11↩12
  2. ECMAScript, Environment Records↩1↩2↩3↩4↩5↩6↩7
  3. MDN, for↩1↩2↩3
  4. React, State as a Snapshot↩1↩2
  5. React, useEffect↩1↩2
  6. MDN, EventTarget.addEventListener↩
  7. MDN, Memory management↩1↩2
  8. Chrome DevTools, Record heap snapshots↩1↩2
  9. React, Removing Effect Dependencies↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning