Scope, Closures & Hoisting

Lexical scope and the scope chain, var vs let/const, hoisting and the temporal dead zone, closures and how they're implemented, the loop-closure bug, and practical uses like memoisation and private state.

Intermediate 3 min readLesson 3 of 12 Interview Q&A

Scope decides where a variable is visible. Closures let a function keep access to variables from where it was defined, even after that code has finished running. Together they're behind module patterns, callbacks, React hooks, and many interview questions.

Lexical scope

JavaScript uses lexical (static) scope: a function's access to variables is determined by where it's written in the source, not where it's called from.

JavaScript
const greeting = "Hello";             // global scope

function outer() {
  const name = "Ada";                 // outer's scope
  function inner() {
    const punctuation = "!";          // inner's scope
    return `${greeting}, ${name}${punctuation}`;   // looks outward through the scope chain
  }
  return inner();
}
inner scopepunctuationlooked up firstouter scopename, innermodule / global scopegreeting, outerlooked up last

Lookup walks this scope chain outward until the name is found, or throws ReferenceError. Inner scopes can shadow outer names.

Scope kinds: global, module (each ES module file), function, and block ({ } for let, const, class).

var vs let / const

varletconst
ScopeFunctionBlockBlock
HoistedYes, initialised to undefinedYes, but uninitialised (TDZ)Yes, uninitialised (TDZ)
Re-declare in same scopeAllowedErrorError
ReassignYesYesNo
Creates global object propertyYes (window.x) at top levelNoNo
JavaScript
if (true) {
  var a = 1;
  let b = 2;
}
console.log(a);   // 1 — var ignores blocks
console.log(b);   // ReferenceError

Hoisting

Before running a scope's code, the engine registers all declarations in it. That's "hoisting" — declarations behave as if moved to the top. What differs is how they're initialised:

JavaScript
console.log(x);        // undefined — var is hoisted AND initialised to undefined
var x = 5;

sayHi();               // works — function declarations are hoisted completely
function sayHi() { console.log("hi"); }

console.log(y);        // ReferenceError: Cannot access 'y' before initialization
let y = 5;

greet();               // TypeError: greet is not a function (var greet is undefined here)
var greet = function () {};

The temporal dead zone (TDZ)

let, const and class bindings exist from the start of their block, but accessing them before the declaration line runs throws. The span between is the TDZ:

JavaScript
let value = "outer";
{
  console.log(value);   // ReferenceError — not "outer"! The inner 'value' is hoisted and in its TDZ
  let value = "inner";
}

Closures

A closure is a function together with references to the variables of the scope where it was created. When makeCounter returns, its local count doesn't disappear — the returned function still references it.

function makeCounter() {
  let count = 0;                       // private: only reachable through the closures
  return {
    increment: () => ++count,
    decrement: () => --count,
    get value() { return count; },
  };
}

const a = makeCounter();
const b = makeCounter();               // independent count
a.increment(); a.increment();
b.increment();
console.log(a.value, b.value);         // 2 1

How it works

Each function call creates an environment record (the variables of that scope) linked to its parent's. A function object stores a hidden reference ([[Environment]]) to the environment it was created in. As long as the function is reachable, so is that environment — the GC can't free it. Engines like V8 optimise by keeping only the variables closures actually use in a heap-allocated "context"; the rest stay on the stack.

[[Environment]]outerincrement()function objectmakeCounter's environmentcount = 2global environment

The classic loop bug

JavaScript
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// 3 3 3 — one shared 'var i' (function-scoped); by the time callbacks run, i is 3

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// 0 1 2 — let creates a NEW binding for each iteration

Before let, the fix was an IIFE that captured each value: (function (j) { setTimeout(() => console.log(j)); })(i).

Practical uses of closures

JavaScript
// 1. Private state / module pattern
const bank = (() => {
  let balance = 0;
  return { deposit: (x) => (balance += x), balance: () => balance };
})();

// 2. Function factories
const multiplier = (factor) => (x) => x * factor;
const double = multiplier(2);

// 3. Memoisation
function memoize(fn) {
  const cache = new Map();
  return (arg) => {
    if (!cache.has(arg)) cache.set(arg, fn(arg));
    return cache.get(arg);
  };
}

// 4. Debounce: wait until calls stop for `ms` milliseconds
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}
const onSearch = debounce((q) => fetchResults(q), 300);

// 5. Once
function once(fn) {
  let done = false, result;
  return (...args) => (done ? result : ((done = true), (result = fn(...args))));
}

React hooks rely on closures too — which is why stale closures happen: an effect or callback captures the state value from the render it was created in. Dependency arrays and functional updates (setCount(c => c + 1)) exist to deal with that.

Key takeaways
  • Scope is lexical: determined by where code is written; lookups walk the scope chain outward.
  • var is function-scoped and initialised to undefined when hoisted; let/const are block-scoped with a TDZ.
  • Function declarations are hoisted whole; function expressions are not.
  • A closure is a function plus its captured environment, which stays alive as long as the function does.
  • let in loops creates a fresh binding per iteration; closures power private state, factories, memoisation and debounce.
Interview questions
QWhat is a closure? Give a practical example.easy

A closure is a function that retains access to variables from the scope where it was defined, even after that scope has returned. For example, a makeCounter function declares a local count and returns an increment function; each call to increment updates the same count, which is private because nothing else can reach it. Debounce, memoisation and module patterns are all built on closures.

QExplain hoisting and the temporal dead zone.medium

Before executing a scope, the engine creates bindings for all its declarations. var bindings are initialised to undefined, so reading them early gives undefined; function declarations are initialised with the whole function. let, const and class bindings are created but left uninitialised; accessing them before their declaration executes throws a ReferenceError. That period is the temporal dead zone.