Skip to content
Kuza Ndoto Academy

Scope & Closures

Beginner → IntermediateChapter 3 · Page 13 of 325 min readUpdated 15 Nov 2026

Scope decides where in your code a variable can be seen and used. A closure is what happens when a function remembers the variables from the place it was created, even after that place has finished running. Together they explain how JavaScript keeps data private and why some bugs happen.

Three levels of scope

  • Global scope: variables declared outside any function or block. Every part of the program can see them.
  • Function scope: variables declared inside a function exist only inside that function.
  • Block scope: let and const declared inside curly braces (an if, a loop, or a bare block) exist only inside those braces.
const school = "Moi Girls";          // global scope

function showClass() {
  const form = "Form 3";            // function scope
  if (true) {
    const stream = "East";          // block scope
    console.log(school, form, stream);
  }
  console.log(school, form);
  // console.log(stream);  would throw ReferenceError: stream is not defined
}

showClass();
// console.log(form);      would throw ReferenceError: form is not defined
Moi Girls Form 3 East Moi Girls Form 3
Global scope · school Function scope (showClass) · form Block scope (if) · stream Code here can use stream, form and school. A lookup starts here and moves outward. Global code sees only school (form and stream don't exist here)
Figure 1. Scopes nest like boxes. Inner code can look outward and use anything in the boxes around it; outer code can never look inside an inner box.

When JavaScript meets a name, it looks in the current scope first, then the one around it, and so on up to the global scope. This chain of lookups is the scope chain. If the name is found nowhere, you get a ReferenceError.

Shadowing

An inner scope may declare a variable with the same name as an outer one. The inner variable shadows (hides) the outer one inside its scope, and the outer one is untouched:

const leader = "Kamau";

function meeting() {
  const leader = "Njeri";
  console.log(leader);
}

meeting();
console.log(leader);
Njeri Kamau

Shadowing is legal but can confuse readers, so use distinct names when you can.

Closures

A function in JavaScript carries a link to the scope where it was created. If a function is returned from another function, it still has access to the outer function's variables, even though the outer function has already finished. That combination of a function and its remembered variables is a closure.

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

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

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

Each call to makeCounter creates a fresh count variable and a new inner function that closes over it. Normally a function's local variables disappear when it returns, but here the inner function still refers to count, so it stays alive. counterA and counterB each have their own private count, which is why counterB() starts again at 1.

makeCounter() has finished count: 3 still alive inner function remembers counterA each counterA() call runs count++ and returns 1, then 2, then 3
Figure 2. A closure is like a backpack: the returned function carries the variables it needs from the scope where it was born.

What closures are good for

Private data. Variables inside a closure can't be reached from outside except through the functions you choose to expose:

function createWallet(owner) {
  let balance = 0;
  return {
    deposit(amount) {
      balance += amount;
      return `${owner} now has KES ${balance}`;
    },
    getBalance() {
      return balance;
    }
  };
}

const wallet = createWallet("Neema");
console.log(wallet.deposit(500));
console.log(wallet.deposit(250));
console.log(wallet.balance);
console.log(wallet.getBalance());
Neema now has KES 500 Neema now has KES 750 undefined 750

wallet.balance is undefined because balance is not a property of the object; it lives only in the closure. Nobody can set it to a million shillings by accident.

Function factories. A function can build customised functions:

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

const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(7), triple(7));
14 21

Closures also power event handlers and timers: a click handler written inside a function can still use that function's variables when the click happens much later.

The classic loop trap: var vs let

This puzzle catches many developers. setTimeout runs a callback later (after 100 milliseconds here):

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log("var:", i), 100);
}
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log("let:", j), 100);
}
var: 3 var: 3 var: 3 let: 0 let: 1 let: 2

With var there is only one i for the whole loop. By the time the callbacks run, the loop has finished and i is 3, so all three closures see 3. With let, each round of the loop gets its own j, so each closure remembers a different value. One more reason to prefer let. (Why the callbacks wait is explained in Callbacks & the Event Loop.)

Common mistake

Assigning to a name you never declared, such as total = 5; without let or const, silently creates a global variable in old, non-strict scripts, and throws a ReferenceError in strict mode and modules. Always declare your variables, and keep as few globals as possible.

Key points

  • Scope is where a variable is visible: global, function or block (let/const in braces).
  • Lookups move outward along the scope chain; outer code can't see inner variables.
  • A closure is a function plus the variables it remembers from where it was created.
  • Closures give private state (counters, wallets) and function factories.
  • In loops, let creates a new variable each round; var shares one.
Up next · Functions, Objects & ArraysObjectsProperties, methods, destructuring and spread.
→

Tip: use the ← and → keys to move between pages.