SyntaxPilot
Courses/JavaScript/Lesson 10

JavaScript · Lesson 10 of 40 · 12 min

Scope, hoisting and closures

queued

These are the notes for JavaScript episode 10. You will learn why one shared variable causes silent bugs, what scope is, global vs local (function) scope, ReferenceError: x is not defined, how inner code sees outer variables (and never the other way round), shadowing, lexical scope, block scope with let/const vs var, hoisting and the temporal dead zone, closures, independent counters, the famous var vs let loop trap, and a mini project: a wallet whose balance nobody can touch directly. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

The problem: one counter, two people

Ravi's app counts chai orders in a variable count at the top of the file. His helper writes a function to count cleaned tables, sees count already exists, and reuses it:

let count = 0;
function chaiOrder() {
  count = count + 1;
  return `Chai order #${count}`;
}
function cleanTables() {
  for (count = 0; count < 3; count++) {}
  return `Cleaned ${count} tables`;
}
console.log(chaiOrder());
console.log(chaiOrder());
console.log(cleanTables());
console.log(chaiOrder());
Chai order #1
Chai order #2
Cleaned 3 tables
Chai order #4

The third order is numbered #4. The loop in cleanTables overwrote count with 3, and the next order added one to that. No error, just wrong numbers on every receipt from now on.

Why it failed: a variable at the top level of the file is visible everywhere, so any function can change it by accident. We need variables that belong to one function only.

Scope: rooms in a house

A house In JavaScript Name
The living room: everyone can use it a variable at the top level of the file global scope
Your own room: your stuff stays inside a variable created inside a function function (local) scope
From your room you can see the hall, not the other way round inner code reads outer variables lexical scope
  • Scope is the area of code where a name (a variable or function) can be seen and used.
  • A variable created inside a function is a local variable. It's created when the function runs and is gone when it ends.
  • A variable at the top level is global: every function can read and change it.

Local variables stay inside

function makeBill() {
  const total = 250;
  console.log("Inside:", total);
}
makeBill();
console.log("Outside:", total);
Inside: 250
ReferenceError: total is not defined

total lived only inside makeBill. Outside, the name doesn't exist, so JavaScript throws ReferenceError: total is not defined. That's exactly what we want: nobody outside can see or change it.

Inner code looks outward; shadowing

const shop = "Ravi's Chai";
function printHeader() {
  const date = "29 Oct";
  console.log(`${shop} - ${date}`);
}
printHeader();
const item = "tea";
function order() {
  const item = "coffee";
  console.log("inside:", item);
}
order();
console.log("outside:", item);
Ravi's Chai - 29 Oct
inside: coffee
outside: tea
  • printHeader uses its own date and the global shop: inner code can read outer variables.
  • Inside order, a new item has the same name as the outer one. Inside the function the inner one wins and hides the outer one. That's shadowing. The outer item is not changed.

How JavaScript finds a name

When your code uses a name, JavaScript looks in the current scope first, then the scope around it, then the next one out, all the way to the global scope. If it's not found anywhere: ReferenceError. This chain of scopes is fixed by where you wrote the code, which is why it's called lexical scope ("lexical" = to do with the written text).

┌ global ─────────────────────────── shop, item = "tea"
│  ┌ function order() ────────────── item = "coffee"
│  │  ┌ { block } ────────────────── let / const
│  │  │   looks here first → then outward →

Golden rule: keep each variable in the smallest scope that works. That alone would have prevented Ravi's bug.

Block scope: let and const vs var

A block is any pair of curly brackets { }: the body of an if, a for loop, or just { } on its own.

Keyword Respects function walls Respects block walls { }
let, const yes yes (block scope)
var yes no, it leaks out
const bill = 120;
if (bill > 100) {
  let discount = 10;
  var note = "big order";
  console.log("discount inside:", discount);
}
console.log("note outside:", note);
console.log("discount outside:", discount);
discount inside: 10
note outside: big order
ReferenceError: discount is not defined

var note leaked out of the if; let discount stayed in its block. A leaking variable is exactly how bugs like Ravi's happen, which is why modern JavaScript uses let and const and almost never var (episode 2's rule, now with the reason).

Hoisting and the temporal dead zone

console.log(a);
var a = 5;
console.log(a);
console.log(greet());
function greet() {
  return "hello";
}
console.log(b);
let b = 7;
undefined
5
hello
ReferenceError: Cannot access 'b' before initialization

Before running any line, JavaScript scans each scope and sets up every declaration. This is called hoisting (as if declarations were lifted to the top):

Declaration Before its line, it is... Using it early gives
var a = 5 set up as undefined undefined (silent)
function greet() {} set up complete it works
let b / const b known, but locked ReferenceError: Cannot access 'b' before initialization
const late = () => ... known, but locked (it's a const) the same ReferenceError (episode 9)

The time between the start of the scope and the let/const line is the temporal dead zone (TDZ). The error is a good thing: it catches the bug, while var silently hands you undefined.

Practical rule: declare first, use after. Then hoisting never surprises you.

Closures: functions that remember

Ravi wants a token counter that nobody else can break. Two obvious attempts both fail:

  • A global counter can be changed by anyone (the bug above).
  • A local counter forgets:
function nextToken() {
  let token = 0;
  token = token + 1;
  return token;
}
console.log(nextToken(), nextToken(), nextToken());
1 1 1

Each call creates a fresh token = 0 and throws it away at the end. We need a variable that is private but survives between calls.

The fix: a token machine with a memory

At the stall In JavaScript
A factory builds a token machine and sets its counter to 0 makeCounter() runs once and creates token = 0
The machine leaves the factory with its counter sealed inside it returns an inner function that uses token
Nobody can open the counter; you can only press the button token is private; only calling the function changes it
function makeCounter() {
  let token = 0;
  return function () {
    token = token + 1;
    return token;
  };
}
const chaiTokens = makeCounter();
console.log(chaiTokens(), chaiTokens(), chaiTokens());
const juiceTokens = makeCounter();
console.log(juiceTokens(), juiceTokens());
console.log(chaiTokens());
console.log(typeof token);
1 2 3
1 2
4
undefined
  • The inner function was written inside makeCounter, so it can see token (lexical scope). It keeps token alive even after makeCounter has finished.
  • A function bundled with the variables it remembers from where it was created is a closure.
  • Every call to makeCounter makes a new token, so chaiTokens and juiceTokens count separately (4 continues the chai count).
  • typeof token outside is undefined: there's no way to reach token except by calling the function. Closures give you private data.

The loop trap: var vs let

setTimeout(fn, 0) runs fn a moment later, after the current code (here, the whole loop) has finished. You'll learn exactly why in the event loop episode.

for (var i = 1; i <= 3; i++) {
  setTimeout(() => console.log("var:", i), 0);
}
for (let j = 1; j <= 3; j++) {
  setTimeout(() => console.log("let:", j), 0);
}
var: 4
var: 4
var: 4
let: 1
let: 2
let: 3
  • var i ignores the loop's block, so there is one i for the whole loop. By the time the arrows run, the loop has pushed it to 4, and all three closures see that same i.
  • let j creates a fresh j for every pass of the loop, so each arrow closes over its own j.
  • Closures remember variables, not values. With let, each pass gets its own variable.

Common mistakes (and what really happens)

You wrote What happens Why Fix
function f() { const total = 5; } then total ReferenceError: total is not defined total is local to f return it, or declare it outside
if (x) { let d = 10; } then d ReferenceError: d is not defined let stays in its block declare d before the if
console.log(b); let b = 7; ReferenceError: Cannot access 'b' before initialization temporal dead zone declare first, use after
console.log(a); var a = 5; (no error) undefined var is hoisted as undefined use let / const
for (var i ...) setTimeout(() => log(i)) (no error) 4 4 4 one shared var i for (let i ...)
two functions reusing one global counter (no error) wrong numbers anyone can change a global local variables or a closure
function nextToken() { let token = 0; ... } (no error) 1 1 1 a local is recreated every call a closure (makeCounter)

Mini project: a private wallet

function makeWallet(owner, balance = 0) {
  const history = [];
  return {
    pay(amount) {
      if (amount > balance) return `${owner}: not enough money`;
      balance -= amount;
      history.push(-amount);
      return `${owner} paid Rs ${amount}, left Rs ${balance}`;
    },
    addMoney(amount) {
      balance += amount;
      history.push(amount);
      return `${owner} added Rs ${amount}, now Rs ${balance}`;
    },
    history: () => history.join(", "),
  };
}
const asha = makeWallet("Asha", 100);
console.log(asha.pay(30));
console.log(asha.pay(200));
console.log(asha.addMoney(50));
console.log(asha.history());
console.log(asha.balance);
Asha paid Rs 30, left Rs 70
Asha: not enough money
Asha added Rs 50, now Rs 120
-30, 50
undefined
  • makeWallet returns an object (episode 8) with three methods. All three are closures over the same balance, owner and history.
  • pay checks the rule (enough money?) before changing balance. Nobody can skip the check, because asha.balance doesn't exist: undefined.
  • This is how real apps protect data: the only way in is through functions that enforce the rules.

Try adding a getBalance method.

Practice

  1. Write makeGreeter(greeting) that returns a function: makeGreeter("Hello")("Asha") gives Hello, Asha!.
  2. Write once(fn): the returned function runs fn only the first time and returns the first result after that.
  3. Add a getBalance method to the wallet.
  4. Predict, then run: the var vs let loop with setTimeout.
Solutions and hints
function makeGreeter(greeting) {
  return (name) => `${greeting}, ${name}!`;
}
const hello = makeGreeter("Hello");
const namaste = makeGreeter("Namaste");
console.log(hello("Asha"), namaste("Ravi"));
function once(fn) {
  let done = false;
  let result;
  return (...args) => {
    if (!done) {
      done = true;
      result = fn(...args);
    }
    return result;
  };
}
const welcome = once((name) => { console.log(`Welcome gift for ${name}!`); return "gift"; });
console.log(welcome("Meena"));
console.log(welcome("Kiran"));
Hello, Asha! Namaste, Ravi!
Welcome gift for Meena!
gift
gift
  1. Each greeter remembers its own greeting: two closures from one factory.
  2. done and result are private to each once wrapper. ...args (rest and spread, episode 12) passes along whatever arguments it gets.
  3. Inside the returned object: getBalance: () => balance,. It reads the private balance without letting anyone change it.
  4. var: 4 three times, then let: 1, let: 2, let: 3 (see "The loop trap").

Quick quiz

What does this print?

function make() {
  let n = 10;
  return () => ++n;
}
const a = make(), b = make();
a();
console.log(a(), b());
  • A. 11 11
  • B. 12 11
  • C. 12 12
  • D. 11 12
Answer

B. a and b each have their own n. a() runs twice (11, then 12); b() runs once (11).

Interview questions

  • What is scope? What are global, function and block scope?
  • What's the difference between var, let and const in terms of scope?
  • What is lexical scope? How does JavaScript look up a variable name?
  • What is shadowing?
  • What is hoisting? How are var, let/const and function declarations hoisted differently?
  • What is the temporal dead zone?
  • What is a closure? Give a practical example.
  • How do closures let you create private variables?
  • Why does a for (var i ...) loop with setTimeout print the same number three times, and how does let fix it?
  • Two counters are made from the same makeCounter. Do they share their count? Why not?

Glossary

Term Meaning Example
Scope the area of code where a name can be seen a local variable's scope is its function
Global scope the top level of the file; visible everywhere let count = 0; at the top
Function (local) scope variables created inside a function, visible only there const total = 250; inside makeBill
Local variable a variable that lives inside a function or block token inside nextToken
Block any { }: an if body, a loop body if (x) { ... }
Block scope let/const are visible only inside their block let discount in the if
ReferenceError using a name that isn't available here (or yet) total is not defined
Shadowing an inner variable with the same name hides the outer one item = "coffee" inside order
Lexical scope scopes are decided by where the code is written inner functions see outer variables
Scope chain the lookup order: current scope → outer → ... → global shop found in global
Hoisting declarations are set up before any line runs greet() works before its line
Temporal dead zone (TDZ) the time before a let/const line when it's locked Cannot access 'b' before initialization
var the old keyword: function-scoped, leaks out of blocks, hoisted as undefined var note
Closure a function plus the variables it remembers from where it was created the function returned by makeCounter
Factory function a function that builds and returns new functions or objects makeCounter, makeWallet
Private data data reachable only through certain functions the wallet's balance
setTimeout(fn, ms) runs fn later, after the current code finishes setTimeout(() => log(i), 0)
typeof tells the type of a value; undefined for an unknown name typeof token → undefined

Summary

  • Scope is where a name can be seen. Local variables stay inside their function; inner code looks outward, never inward. Same name inside = shadowing.
  • let and const stay inside their block; var leaks out. Use let/const.
  • Hoisting: var starts as undefined, function declarations are ready, let/const are locked until their line (the TDZ). Declare first, use after.
  • A closure is a function plus the variables it remembers. It gives you state that is private and survives between calls.
  • Closures remember variables, not values: in loops, let gives each pass its own variable.

Next episode: map, filter and reduce. Ravi has a day of orders and wants GST on each, only the big ones, and the total, without writing a loop for every job.