Closures and Scope

Published by Brayan K

A clear, in-depth guide to closures in JavaScript — with worked examples, common pitfalls, and a practice quiz.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

One factory call creates state; returned functions keep access to it

A closure combines a function with access to the lexical bindings around its creation. The outer function does not need to stay on the call stack. When a returned function uses a binding from that call, the binding can remain available after the call has finished.

function createCounter() {
  let count = 0; // One binding belongs to each createCounter call.
  return {
    increment() { count += 1; return count; },
    read() { return count; }
  };
}
const first = createCounter();
const second = createCounter(); // A new call creates independent state.
console.log(first.increment());
console.log(first.increment());
console.log(first.read(), second.read());
console.log(second.increment());
console.log(first.read(), second.read());

// ✅ Expected output:
// 1
// 2
// 2 0
// 1
// 2 1

increment and read created by one call both access that call’s count. Calling createCounter again creates another count binding. The methods do not receive a frozen copy of zero. Scope & var/let/const (TDZ) owns scope boundaries, shadowing and initialization; here we follow the lifetime and sharing of those bindings.

function createCounter() {
  let count = 0;
  return () => ++count;
}
const original = createCounter();
const alias = original;
const separate = createCounter();
console.log(alias === original);
console.log(original(), alias(), separate());

// ✅ Expected output:
// true
// 1 2 1

original and alias are two references to the same function and state. separate comes from a new call. If two controls unexpectedly share a counter, check whether you copied a reference when you meant to call the factory.

A captured binding is live; a computed value is a snapshot

function createStatus() {
  let count = 0;
  const initialLabel = "Count: " + count;
  return {
    increment() { count++; },
    live() { return "Count: " + count; },
    initial() { return initialLabel; }
  };
}
const status = createStatus();
status.increment();
status.increment();
console.log(status.live());
console.log(status.initial());

// ✅ Expected output:
// Count: 2
// Count: 0

live reads count each time it runs. initial reads a different binding, initialLabel, whose string was calculated once. A stale result does not mean closures randomly stopped updating: inspect which expression ran when the function was created and which expression runs when it is called.

function makeGreeting(name) {
  return () => "Hello " + name;
}
const greet = makeGreeting("Ada");
function run(callback) {
  const name = "Mina";
  return callback();
}
console.log(run(greet));

// ✅ Expected output:
// Hello Ada

The name used by greet is the parameter of makeGreeting, not the local variable of whoever calls it. This is lexical scope. The call-site rules for this are a separate mechanism owned by The this Keyword.

function reader(record) {
  return () => record.name;
}
let person = { name: "Ada" };
const read = reader(person);
person.name = "Mina";
console.log(read());
person = { name: "Sam" };
console.log(read());
console.log(person.name);

// ✅ Expected output:
// Mina
// Mina
// Sam

reader received a reference to the original object. Mutating that object is visible through the retained reference. Reassigning the caller’s person variable does not reassign reader’s separate record parameter. Spread & Rest Operators owns shallow copies when shared references are unwanted.

Return the function, and retain it for the lifetime you intend

function makeCounter() {
  let count = 0;
  function increment() { return ++count; }
  return increment();
}
const next = makeCounter();
console.log(typeof next, next);
next();

// ✅ Expected output:
// number 1

// ✅ Expected error:
// TypeError: next is not a function

return increment() runs immediately and returns its number. The caller cannot call that number. Return increment itself when the caller should decide when to run it.

function makeCounter() {
  let count = 0;
  return () => ++count;
}
console.log(makeCounter()());
console.log(makeCounter()());
const next = makeCounter();
console.log(next());
console.log(next());

// ✅ Expected output:
// 1
// 1
// 1
// 2

The first two expressions each create a counter, use it once and discard the returned function. The later calls reuse one retained function. This distinction matters when a setup function is run repeatedly. It does not require a global counter: store the function in the object or scope that owns its lifetime.

Callbacks created with a shared loop binding all read that shared binding. Scope & var/let/const (TDZ) owns the var-versus-let loop comparison. Passing a value into a factory is another way to create a distinct parameter binding for each callback:

function labelFor(id) {
  return () => "Item " + id;
}
const callbacks = [];
for (var id = 0; id < 3; id++) {
  callbacks.push(labelFor(id));
}
console.log(callbacks.map(callback => callback()).join(" | "));
console.log(id);

// ✅ Expected output:
// Item 0 | Item 1 | Item 2
// 3

Encapsulation depends on what your API exposes

An outer local is not automatically a property of the returned object. The counter API can control access to that binding, but its methods can still choose to expose or modify it. Closures in frontend code are not a place to hide credentials from the person running that code.

function createCounter() {
  let count = 0;
  return { increment: () => ++count, read: () => count };
}
const counter = createCounter();
console.log(counter.count);
counter.count = 99;
console.log(counter.count);
console.log(counter.increment(), counter.read());

// ✅ Expected output:
// undefined
// 99
// 1 1
function createCounter() {
  let internalCount = 0;
  return () => ++internalCount;
}
const next = createCounter();
console.log(next());
console.log(internalCount);

// ✅ Expected output:
// 1

// ✅ Expected error:
// ReferenceError: internalCount is not defined

Returning an internal mutable object gives callers access to that object, even though the variable that holds it is local. The first API below leaks its array. The second returns a fresh array of strings, so changing that returned array does not change its internal list.

function leakyList() {
  const items = [];
  return { add: value => items.push(value), read: () => items };
}
const leaky = leakyList();
leaky.add("Ada");
leaky.read().push("Mina");
console.log(leaky.read().join(","));

function protectedList() {
  const items = [];
  return { add: value => items.push(value), read: () => [...items] };
}
const list = protectedList();
list.add("Ada");
const copy = list.read();
copy.push("Mina");
console.log(copy.join(","));
console.log(list.read().join(","));

// ✅ Expected output:
// Ada,Mina
// Ada,Mina
// Ada

The copy is shallow. If the list contained mutable records, those records would still be shared unless the API handled them separately. Encapsulation is a contract about reachable state, not just the presence of a nested function.

A retained listener needs an explicit end to its lifetime

An event target retains its registered listener. If that listener closes over state, keeping the registration alive also keeps that state reachable through the listener. Return a disposer when the owner needs a clear way to stop listening. This local EventTarget fixture works without a DOM or a timer.

function watch(target, prefix) {
  let count = 0;
  const listener = () => {
    count++;
    console.log(prefix, count);
  };
  target.addEventListener("tick", listener);
  return () => target.removeEventListener("tick", listener);
}
const target = new EventTarget();
const stop = watch(target, "seen");
target.dispatchEvent(new Event("tick"));
target.dispatchEvent(new Event("tick"));
stop();
stop();
target.dispatchEvent(new Event("tick"));
console.log("stopped");

// ✅ Expected output:
// seen 1
// seen 2
// stopped

The third event produces no listener output because the registration was removed. Calling the disposer again is harmless. This verifies behavior, not the moment memory is reclaimed; a retained disposer can itself retain references. Events owns listener identity, options and AbortSignal removal. JavaScript Memory Management & Garbage Collection owns reachability and memory investigation.

A closure can own a cache, but the cache still needs a contract

This small example remembers only the most recent argument/result pair for a synchronous function of one finite number. Object.is compares the key, and a separate hasValue flag distinguishes an empty cache from a cached undefined. A new argument replaces the entry. Failed calls do not update it.

function rememberLast(fn) {
  let hasValue = false;
  let lastArgument;
  let lastResult;
  return value => {
    if (!Number.isFinite(value)) throw new TypeError("Expected a finite number");
    if (hasValue && Object.is(value, lastArgument)) return lastResult;
    const result = fn(value);
    lastArgument = value;
    lastResult = result;
    hasValue = true;
    return result;
  };
}
let calls = 0;
const twice = rememberLast(value => { calls++; return value * 2; });
console.log(twice(2), twice(2), calls);
console.log(twice(3), twice(2), calls);
let emptyCalls = 0;
const empty = rememberLast(() => { emptyCalls++; return undefined; });
console.log(empty(0), empty(0), emptyCalls);
let failures = 0;
const failing = rememberLast(() => { failures++; throw new Error("Failed"); });
for (let attempt = 0; attempt < 2; attempt++) {
  try { failing(1); } catch (error) { console.log(error.message); }
}
console.log("failures", failures);

// ✅ Expected output:
// 4 4 1
// 6 4 3
// undefined undefined 1
// Failed
// Failed
// failures 2

The count proves that selected repeated calls avoid running fn. It does not prove a speedup: lookup, allocation, input size and workload matter. Use this only when the result depends on that input and suppressing repeated calls is acceptable. A returned object would be the same cached reference, not a fresh copy. Advanced Scope, Closures & Lexical Environments owns broader closure patterns; general caching and performance measurement need their own contracts.

Guided exercise: keep a stepper’s state between calls

Complete the three blanks. Each factory call should own a value and step; each invocation of its returned function updates that value.

function makeStepper(start, step) {
  ___ value = start; // 👉 replace ___ with let
  ___ () => { // 👉 replace ___ with return
    value += ___; // 👉 replace ___ with step
    return value;
  };
}
const byTwo = makeStepper(0, 2);
const byFive = makeStepper(10, 5);
console.log(byTwo(), byTwo());
console.log(byFive());
console.log(byTwo());

// ✅ Expected output:
// 2 4
// 15
// 6

Independent brief: a bounded counter with independent instances

Write createCounter(limit). Accept an integer limit from 0 through 100, otherwise throw RangeError("Limit must be an integer from 0 to 100"). Start count at zero. Return increment, reset and read methods. increment adds one and returns the new count, but at the limit throws RangeError("Counter is full") without changing count. reset sets count to zero and returns zero. read returns count. Methods must keep working when extracted from the object.

Check two independent instances, the full state, reset, a zero limit, invalid limits and an extracted increment method. No writable count property is needed.

function createCounter(limit) {
  if (!Number.isInteger(limit) || limit < 0 || limit > 100) {
    throw new RangeError("Limit must be an integer from 0 to 100");
  }
  let count = 0;
  return {
    increment() {
      if (count === limit) throw new RangeError("Counter is full");
      count++;
      return count;
    },
    reset() { count = 0; return count; },
    read() { return count; }
  };
}
const first = createCounter(2);
const second = createCounter(1);
const increment = first.increment;
console.log(increment(), increment());
console.log(first.read(), second.read());
try { increment(); } catch (error) { console.log(error.message); }
console.log("unchanged", first.read());
console.log("reset", first.reset(), first.read());
console.log("independent", second.increment(), first.read());
const closed = createCounter(0);
try { closed.increment(); } catch (error) { console.log(error.message); }
console.log("zero", closed.read());
for (const limit of [-1, 1.5, 101, "2"]) {
  try { createCounter(limit); } catch (error) { console.log(error.message); }
}

// ✅ Expected output:
// 1 2
// 2 0
// Counter is full
// unchanged 2
// reset 0 0
// independent 1 0
// Counter is full
// zero 0
// Limit must be an integer from 0 to 100
// Limit must be an integer from 0 to 100
// Limit must be an integer from 0 to 100
// Limit must be an integer from 0 to 100

The methods refer to count and limit through their creation environment, so extracting increment does not depend on a receiver. The limit check happens before the mutation, preserving state on failure. This is a local teaching counter, not a security boundary or persistent database.

Practice quiz

What does this complete program print? function make() { let n = 0; return () => ++n; } const a = make(), b = make(); console.log(a(), a(), b());

  • 1 2 1
  • 1 2 3
  • 1 1 1
  • 0 1 0

Answer: 1 2 1. Each call to make creates a separate n binding; repeated calls to a reuse its binding.

What does this complete program print? let value = 1; const read = () => value; value = 4; console.log(read());

  • 1
  • 4
  • undefined
  • ReferenceError

Answer: 4. The closure reads the binding when called; it does not freeze the initial primitive value.

What does this complete program print? let count = 0; const label = "Count " + count; const read = () => label; count++; console.log(read());

  • Count 1
  • Count undefined
  • Count 0
  • 1

Answer: Count 0. The label string was computed earlier and its binding has not changed.

What does this complete program print? function make() { let n = 0; return () => ++n; } const a = make(); const b = a; console.log(a(), b());

  • 1 1
  • 0 1
  • 2 1
  • 1 2

Answer: 1 2. b references the same function as a, so both calls update the same n.

What does this complete program print? function make(name) { return () => name; } const read = make("Ada"); function run(fn) { const name = "Mina"; return fn(); } console.log(run(read));

  • Ada
  • Mina
  • undefined
  • ReferenceError

Answer: Ada. The closure resolves the parameter where it was created, not the caller’s local name.

What does this complete program print? function make() { let n = 0; return () => ++n; } console.log(make()(), make()());

  • 1 2
  • 1 1
  • 0 0
  • 2 2

Answer: 1 1. Each expression creates a new counter and calls it once.

What does this complete program print? function make() { let count = 0; return { read: () => count }; } const counter = make(); counter.count = 9; console.log(counter.read(), counter.count);

  • 9 9
  • 0 0
  • 0 9
  • undefined 9

Answer: 0 9. The added property and the captured local binding are separate storage locations.

What does this complete program print? function reader(record) { return () => record.name; } const record = { name: "Ada" }; const read = reader(record); record.name = "Mina"; console.log(read());

  • Ada
  • undefined
  • TypeError
  • Mina

Answer: Mina. The parameter still references the same mutable object, whose name has changed.

Continue this course

Related lessons