Reading history

JavaScript Scope, Hoisting and Closures Explained

6 min read 2 views

Understand JavaScript scope, hoisting and the temporal dead zone, var vs let in loops, and closures for private state, factories, memoization and once().

Every variable in JavaScript lives in a scope: the part of the code where it can be seen. Scope decides why a variable is “not defined” in one place and available in another, why var and let behave differently in loops, and why some variables seem to exist before the line that declares them (hoisting). On top of scope sits one of JavaScript’s most useful ideas, the closure: a function that remembers the variables around it, even after the outer function has finished.

In this lesson you will learn

  • Global, function and block scope, and shadowing
  • How hoisting treats functions, var, let and const
  • The temporal dead zone
  • What a closure is and how it keeps private state
  • Practical closures: factories, memoization and once()

You should know functions and variables.

Scope and Hoisting

"use strict";
// 1. Block scope: let and const live only inside their { }
const course = "JavaScript";
if (true) {
  const course = "Python";            // a different variable that shadows the outer one
  let lessons = 30;
  console.log("inside:", course, lessons);
}
console.log("outside:", course, typeof lessons);   // lessons does not exist here

// 2. Hoisting: function declarations can be called before they appear
console.log(square(4));
function square(n) { return n * n; }

// var is hoisted and starts as undefined; let/const are in the "temporal dead zone"
console.log("var before declaration:", early);
var early = "set later";
try {
  console.log(late);
} catch (e) {
  console.log(e.name + ":", e.message);
}
let late = "set later";

// 3. var vs let in loops with callbacks
const withVar = [], withLet = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);  // one shared i
for (let j = 0; j < 3; j++) withLet.push(() => j);  // a new j each time round
console.log("var:", withVar.map(f => f()), "let:", withLet.map(f => f()));

Output

inside: Python 30
outside: JavaScript undefined
16
var before declaration: undefined
ReferenceError: Cannot access 'late' before initialization
var: [ 3, 3, 3 ] let: [ 0, 1, 2 ]
  • Variables made with let and const have block scope: they exist only inside the nearest { }. The inner course shadows the outer one, which is unchanged afterwards. Outside the block, lessons does not exist, so typeof reports undefined.
  • Hoisting means declarations are processed before the code runs. A function declaration is hoisted completely, so square(4) works on a line above it.
  • A var declaration is hoisted but its value is not: early exists from the start with the value undefined.
  • let and const are hoisted too, but reading them before their line throws a ReferenceError. The stretch of code before the declaration is called the temporal dead zone. This turns silent bugs into clear errors.
  • In the loops, var i is one variable shared by every callback, so all three see its final value, 3. let j creates a fresh variable for each pass, so each callback keeps its own value.

Closures in Practice

"use strict";
// A closure: an inner function keeps access to variables of the function that created it
function makeCounter(start = 0) {
  let count = start;                  // private: nothing outside can reach it directly
  return {
    increment() { count++; return count; },
    reset() { count = start; return count; },
    get value() { return count; },
  };
}
const visits = makeCounter();
const likes = makeCounter(10);
visits.increment(); visits.increment();
likes.increment();
console.log("visits:", visits.value, "likes:", likes.value, "count:", visits.count);

// Function factories: each call remembers its own settings
function makeDiscount(percent) {
  return price => Math.round(price * (1 - percent / 100));
}
const eid = makeDiscount(20), member = makeDiscount(5);
console.log("Eid price:", eid(1500), "member price:", member(1500));

// Memoization: a closure keeps a cache between calls
function memoize(fn) {
  const cache = new Map();
  return n => {
    if (!cache.has(n)) cache.set(n, fn(n));
    return cache.get(n);
  };
}
let calls = 0;
const slowSquare = n => { calls++; return n * n; };
const fastSquare = memoize(slowSquare);
console.log(fastSquare(9), fastSquare(9), fastSquare(12), "real calls:", calls);

// once(): run a function only the first time
function once(fn) {
  let done = false, result;
  return (...args) => {
    if (!done) { done = true; result = fn(...args); }
    return result;
  };
}
const init = once(() => { console.log("connecting..."); return "connected"; });
console.log(init(), init());

Output

visits: 2 likes: 11 count: undefined
Eid price: 1200 member price: 1425
81 81 144 real calls: 2
connecting...
connected connected
  • When makeCounter returns, its variable count is not thrown away, because the returned methods still use it. A function together with the variables it remembers is a closure.
  • Each call creates a new, separate count: visits and likes never affect each other. Nothing outside can read count directly (visits.count is undefined), which gives true private state.
  • A function factory such as makeDiscount(20) returns a small function that remembers its own percent.
  • memoize keeps a Map in its closure. The second fastSquare(9) comes from the cache, so the slow function ran only twice for three calls.
  • once remembers whether it has already run. Setup code such as a database connection often uses this pattern.

Scope Rules at a Glance

DeclarationScopeHoisted?Use before the lineRe-declare?
varFunctionYes, as undefinedGives undefinedYes
letBlockYes, but uninitialisedReferenceErrorNo
constBlockYes, but uninitialisedReferenceErrorNo
function f() {}Function or blockFullyWorksAvoid
const f = () => {}BlockLike constReferenceErrorNo

Common Mistakes

  1. Using var in loops with callbacks, so every callback sees the last value. Use let.
  2. Forgetting to declare a variable. In non-strict code, total = 5 silently creates a global; in strict mode it throws.
  3. Expecting each closure to get a copy of a variable. Closures share the variable itself, so later changes are visible.
  4. Keeping large data alive by accident in a closure that lives forever, such as an event listener that is never removed.

Practice Exercises

Exercise 1. Write makeIdGenerator(prefix) that returns a function giving "S-1", "S-2" and so on.

Show answer
function makeIdGenerator(prefix) {
  let n = 0;
  return () => `${prefix}-${++n}`;
}
const nextStudent = makeIdGenerator("S");
console.log(nextStudent(), nextStudent());   // S-1 S-2

Exercise 2. What does this print, and why? console.log(x); let x = 1;

Show answer

It throws ReferenceError: Cannot access 'x' before initialization. The let declaration is hoisted, but x is in its temporal dead zone until the declaration line runs.

Frequently Asked Questions

Is every function in JavaScript a closure?

Technically yes: every function remembers the scope where it was created. The term usually refers to the interesting case, where an inner function outlives its outer function and keeps using its variables.

Should I still use var?

No. Use const by default and let when a variable must be reassigned. var appears in older code, so it is worth understanding, but its function scope and hoisting cause avoidable bugs.

Summary

  • let and const are block-scoped; var is function-scoped.
  • Function declarations are fully hoisted; let and const have a temporal dead zone.
  • A closure is a function that remembers the variables of the scope it was created in.
  • Closures give private state, factories, caches and run-once helpers.

Next: Destructuring, Spread and Rest.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *