JavaScript – Closures and Scope

By Published 9 min read

JavaScript - Closures and Scope

Introduction:

Here is a small puzzle. A function runs, returns, and is finished. Its local variables should be gone. Yet somehow, another function can still read and even change them, minutes later. How?

The answer is a closure, one of the most important ideas in JavaScript. Closures are behind private variables, event handlers, React hooks, debounce in search boxes, and almost every callback you have ever written. They also cause one of the most famous interview bugs in the language.

To understand closures, you first need to understand scope: the rules that decide where a variable can be seen. In this lesson we will learn the three kinds of scope, how JavaScript looks variables up through the scope chain, what a closure is and why it works, and a set of practical patterns built on closures. We will finish with the classic loop bug, hoisting, and common mistakes.

This lesson builds on JavaScript Variables and JavaScript Functions. Every example was run with Node.js, and the comments show the real output.

Part 1: Scope

1. What Is Scope?:

Scope is the area of your code where a variable exists and can be used. Think of it like rooms in a house. Something kept in the living room can be used by everyone in the house, but something kept inside your bedroom can only be used in that room.

JavaScript has three main kinds of scope:

  • Global (or module) scope: variables declared outside any function or block. They can be used everywhere in the file.
  • Function scope: variables declared inside a function. They exist only inside that function.
  • Block scope: variables declared with let or const inside curly braces { }, such as an if or a for. They exist only inside that block.
const site = "khanwaseem.com";          // global/module scope

function greet() {
  const message = "Hello";              // function scope
  if (true) {
    const name = "Zara";                // block scope
    var legacy = "I leak out of the block";
    console.log(`${message}, ${name} from ${site}`);
  }
  console.log(legacy);
  console.log(name);
}

greet();
// Hello, Zara from khanwaseem.com
// I leak out of the block
// ReferenceError: name is not defined

Look at legacy. It was declared with var inside the if block, but it is still visible after the block ends. That’s because var ignores block scope; it only respects function scope. let and const respect both. This difference is the reason modern JavaScript uses let and const and avoids var.

2. The Scope Chain and Shadowing:

Scopes are nested inside each other, like boxes inside boxes. When JavaScript meets a variable name, it looks in the current scope first. If it doesn’t find it, it looks in the parent scope, then the parent’s parent, all the way out to the global scope. This path is called the scope chain.

If an inner scope declares a variable with the same name as an outer one, the inner one shadows (hides) the outer one:

const color = "black";

function outer() {
  const color = "white";
  function inner() {
    console.log(color);   // finds outer's color first
  }
  inner();
}

outer();              // white
console.log(color);   // black

inner has no color of its own, so it looks one level out and finds "white" in outer. It never needs to reach the global "black". The global variable was never changed; it was just hidden inside outer.

The lookup only goes outwards, never inwards. A parent can never see variables declared inside its children.

3. Lexical Scope:

Here is an important question: when a function looks up a variable, does it use the scope where the function was written, or the scope where it is called?

const x = "global";

function show() {
  console.log(x);
}

function run() {
  const x = "local";
  show();
}

run();   // global

It prints "global". Even though show is called from inside run, where x is "local", it uses the x from where show was defined. This is called lexical scope (or static scope): a function’s scope is decided by its position in the source code, not by who calls it.

This one rule is the key to understanding closures.

Part 2: Closures

4. What Is a Closure?:

A closure is a function together with the variables from the scope where it was created. Because of lexical scope, a function always remembers its birthplace, and it keeps access to those variables even after the outer function has finished running.

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

const counterA = makeCounter();
const counterB = makeCounter();

console.log(counterA(), counterA(), counterA());   // 1 2 3
console.log(counterB());                           // 1

Let’s walk through it:

  • makeCounter() runs, creates count = 0, and returns the inner function. Then makeCounter is finished.
  • Normally count would be thrown away. But the returned function still refers to it, so JavaScript keeps it alive.
  • Every call to counterA() reads and updates that same count.
  • counterB came from a separate call to makeCounter, so it has its own separate count, starting at 0.

A good mental picture: every function carries an invisible backpack holding the variables it needs from where it was created. Wherever the function goes, the backpack goes with it.

5. Closures Capture Variables, Not Values:

A closure doesn’t take a snapshot of the value at the moment it was created. It keeps a live link to the variable itself, so it always sees the latest value:

function makeGreeter() {
  let greeting = "Hi";
  const greet = (name) => `${greeting}, ${name}`;
  greeting = "Namaste";      // changed after greet was created
  return greet;
}

console.log(makeGreeter()("Imran"));   // Namaste, Imran

greet was created while greeting was "Hi", but it printed "Namaste", because it reads the variable when it runs. Keep this in mind; it explains the loop bug later in this lesson.

Part 3: Practical Patterns

6. Private State:

JavaScript objects normally expose all their properties. Closures let you create data that only your functions can touch:

function createBankAccount(initial) {
  let balance = initial;          // private: not a property of the object

  return {
    deposit(amount) {
      if (amount <= 0) throw new Error("Amount must be positive");
      balance += amount;
      return balance;
    },
    withdraw(amount) {
      if (amount > balance) throw new Error("Insufficient funds");
      balance -= amount;
      return balance;
    },
    getBalance() {
      return balance;
    },
  };
}

const account = createBankAccount(1000);
console.log(account.deposit(500), account.withdraw(200), account.getBalance());
// 1500 1300 1300

console.log(account.balance);   // undefined: there is no such property
account.withdraw(5000);         // Error: Insufficient funds

Nobody outside can write account.balance = 1000000. The only way to change the balance is through deposit and withdraw, which check the rules. This is encapsulation, achieved with nothing but a function.

Modern classes can do the same with private fields (#count), which are also truly private:

class Counter {
  #count = 0;
  inc() { return ++this.#count; }
}

const c = new Counter();
c.inc();
console.log(c.inc(), c.count);   // 2 undefined

Both approaches are fine. Closures are common in functional-style code and React; private fields are common in class-based code.

7. Function Factories:

A function that builds and returns other functions, each remembering its own settings, is called a factory:

function multiplier(factor) {
  return (n) => n * factor;
}

const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5), triple(5));   // 10 15

A useful real-world version creates an expensive object once and reuses it through a closure:

const formatINR = ((fmt) => (n) => fmt.format(n))(
  new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" })
);

console.log(formatINR(1234567.5));   // ₹12,34,567.50

The Intl.NumberFormat object is created once, and every call to formatINR reuses it from the closure.

8. once, memoize and debounce:

Many well-known utility functions are just closures that remember something between calls.

once runs a function only the first time, and remembers the result:

function once(fn) {
  let called = false, result;
  return function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}

const init = once(() => {
  console.log("Connecting to database...");
  return "connection#1";
});

console.log(init());
console.log(init());
// Connecting to database...
// connection#1
// connection#1

memoize remembers previous results in a cache that lives in the closure:

function memoize(fn) {
  const cache = new Map();
  return function (n) {
    if (cache.has(n)) return cache.get(n);
    const result = fn(n);
    cache.set(n, result);
    return result;
  };
}

let calls = 0;
const slowSquare = (n) => { calls++; return n * n; };
const fastSquare = memoize(slowSquare);

console.log(fastSquare(12), fastSquare(12), fastSquare(5), "calls:", calls);
// 144 144 25 calls: 2

fastSquare(12) was asked for twice but slowSquare only ran once for it.

debounce waits until calls stop for a while, then runs once. The timer lives in the closure, so every call can cancel the previous one:

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

const search = debounce((q) => console.log("Searching for:", q), 100);
search("j"); search("ja"); search("jav"); search("java");
// (100 ms later) Searching for: java

Four calls, one search. This is exactly how search boxes avoid sending a request for every keystroke.

9. The Module Pattern:

Before JavaScript had import and export, developers used a closure to create modules with private parts. An IIFE (Immediately Invoked Function Expression) runs once and returns only the public functions:

const cart = (function () {
  const items = [];                       // private

  function total() {
    return items.reduce((sum, it) => sum + it.price * it.qty, 0);
  }

  return {
    add(name, price, qty = 1) { items.push({ name, price, qty }); },
    count() { return items.length; },
    total,
  };
})();

cart.add("Pen", 10, 3);
cart.add("Notebook", 60);
console.log(cart.count(), cart.total(), typeof cart.items);   // 2 90 undefined

Today, ES modules give every file its own scope automatically, so a variable not exported from a file is already private. But you will still see this pattern in older code and libraries.

Part 4: Traps and Details

10. The Classic Loop Bug:

This is one of the most famous JavaScript interview questions:

const fnsVar = [];
for (var i = 0; i < 3; i++) {
  fnsVar.push(() => i);
}
console.log(fnsVar.map((f) => f()));   // [ 3, 3, 3 ]

Why not [0, 1, 2]? Because var is function-scoped, there is only one i for the whole loop. All three functions close over that same variable, and remember from section 5, closures see the current value. By the time they run, the loop has finished and i is 3.

The fix is simply let. With let, JavaScript creates a new binding of the variable for every loop iteration, so each function captures its own copy:

const fnsLet = [];
for (let j = 0; j < 3; j++) {
  fnsLet.push(() => j);
}
console.log(fnsLet.map((f) => f()));   // [ 0, 1, 2 ]

The same thing happens with timers, which is how the bug usually appears in real code:

for (var k = 0; k < 3; k++) setTimeout(() => console.log("var k:", k), 0);
for (let m = 0; m < 3; m++) setTimeout(() => console.log("let m:", m), 0);

// var k: 3
// var k: 3
// var k: 3
// let m: 0
// let m: 1
// let m: 2

11. Hoisting and the Temporal Dead Zone:

JavaScript sets up a scope’s variables before running its code. This is called hoisting, and it behaves differently for var and let/const:

console.log(typeof hoisted, hoisted);   // undefined undefined
var hoisted = 5;

console.log(tdz);
// ReferenceError: Cannot access 'tdz' before initialization
let tdz = 1;
  • A var is created and set to undefined at the start of the scope, so reading it early silently gives undefined, which hides bugs.
  • A let or const also exists from the start of its block, but it can’t be used until its declaration line runs. The time in between is called the temporal dead zone (TDZ), and touching the variable there throws a clear error.

The TDZ is another reason to prefer let and const: mistakes fail loudly instead of quietly.

12. Closures and Memory:

Because a closure keeps its variables alive, it also keeps them in memory for as long as the function itself is reachable. Usually this is exactly what you want. But it can cause leaks when a long-lived function, such as an event listener or a setInterval callback, closes over something large it doesn’t really need:

  • Remove event listeners and clear intervals when a component or page section goes away. In React, return a cleanup function from useEffect.
  • Don’t keep huge arrays or DOM nodes in a closure “just in case”. Copy only the small values the function actually uses.

Modern JavaScript engines are smart: they only keep variables that the inner function actually references, not the entire outer scope.

13. Where You Already Use Closures:

You have probably used closures many times without naming them:

  • Event handlers that use a variable from the surrounding function: button.addEventListener("click", () => alert(user.name)).
  • Callbacks and promises, where the .then() callback uses variables from the function that started the request. See our lesson on Promises and async/await.
  • React hooks: every function inside a component closes over that render’s props and state. Stale state bugs in useEffect are closures seeing old values.
  • Array methods like items.filter((it) => it.price < maxPrice), where maxPrice comes from the outer scope.

Conclusion:

Scope decides where a variable can be seen: global, function or block, with let and const respecting blocks and var ignoring them. JavaScript looks variables up through the scope chain, using the place where a function was written (lexical scope). A closure is a function that remembers the variables of its birthplace, even after that outer function has returned. Closures capture live variables, not frozen values.

With closures we built a counter, a bank account with truly private balance, function factories, once, memoize, debounce and a module. We also fixed the classic var loop bug with let, saw how hoisting and the temporal dead zone work, and learned how to avoid closure-related memory leaks.

In the next lesson we will learn how JavaScript runs asynchronous code with the event loop, including the call stack, the task queue and microtasks.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume