Lesson 2 of 12 · 10 min · Core language

Scope, hoisting and closures

Covers: JavaScript (ECMAScript 2025) in current browsers and Node.js 22 or newer. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • Global, function and block scope, and the scope chain
  • How hoisting works for var, let, const and functions
  • The temporal dead zone
  • What a closure is and why it is useful
  • The classic loop-with-callback bug, and private state with closures

In simple words

Scope answers "where can I see this variable?" A variable made inside a function is like a note in your own pocket: other functions cannot see it, but functions inside yours can. A closure is what happens when an inner function carries those pockets with it: it remembers the variables from where it was created, even after the outer function has finished. Closures are everywhere in JavaScript, in event handlers, callbacks and React hooks.

Words to know

  • Scope: the region of code where a variable can be used.
  • Hoisting: JavaScript processing declarations before running the code.
  • Closure: a function together with the variables from the place where it was defined.
  • Lexical scope: scope decided by where code is written, not where it is called.

Scope

JavaScript has three kinds of scope:

  • Global scope: variables declared outside any function or block; visible everywhere (in browsers they hang on window if declared with var). Keep these to a minimum.
  • Function scope: variables declared inside a function (with var, let, const) are visible only in that function.
  • Block scope: let and const are limited to the nearest { } (an if, a for, a block). var ignores blocks.
function demo() {
  if (true) {
    var a = 1;       // function-scoped: visible in the whole function
    let b = 2;       // block-scoped: visible only inside this if
    const c = 3;
  }
  console.log(a);    // 1
  console.log(b);    // ReferenceError: b is not defined
}

Lexical (static) scope: the scope is decided by where the code is written. An inner function can see variables of the functions that enclose it, looking outward step by step: this chain is the scope chain.

const rate = 0.18;                    // outer scope
function price(amount) {
  const gst = amount * rate;          // price can see rate
  function total() {
    return amount + gst;              // total can see amount and gst
  }
  return total();
}

An inner variable with the same name shadows the outer one (legal but confusing; linters warn). Avoid accidental globals: assigning to an undeclared variable (count = 1 without let) creates a global in sloppy mode. ES modules and classes are always strict mode, which makes that an error; add "use strict" in old scripts.

Hoisting

Before running a scope, JavaScript registers its declarations. What you can use before the declaration depends on the kind:

Declaration Before its line
function declaration (function f() {}) fully hoisted: callable earlier
var x = 1 the name is hoisted and set to undefined; the assignment stays in place
let, const, class hoisted but uninitialised: using them before the line throws ReferenceError (the temporal dead zone)
function expression (const f = function(){}, arrow functions) only as hoisted as the variable they are assigned to
console.log(hello());         // "hi": function declarations work early
function hello() { return "hi"; }

console.log(x);               // undefined (var is hoisted, not assigned)
var x = 5;

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

greet();                      // TypeError: greet is not a function
var greet = () => "hello";    // only the name `greet` was hoisted, as undefined

The temporal dead zone (TDZ) is the span from the start of a block until the let or const line runs. It turns the var habit of silently getting undefined into a loud error, which is the right behaviour. Practical rules: declare variables at the top of their scope (or right where first needed), use const and let, and write function declarations or arrow functions before you use them.

Closures

A closure is created whenever a function is created: the function keeps a reference to the variables of the scopes around it, and keeps them alive even after those scopes have finished.

function makeCounter() {
  let count = 0;                 // private to makeCounter
  return function () {
    count += 1;
    return count;
  };
}

const next = makeCounter();
next();   // 1
next();   // 2
const other = makeCounter();     // a separate closure with its own count
other();  // 1

makeCounter has finished, yet the returned function still reads and updates count. Nobody else can touch count: this is private state (the module pattern).

Useful patterns built on closures:

// function factories
const multiplyBy = (n) => (x) => x * n;
const double = multiplyBy(2);
double(21);                      // 42

// private data
function createAccount(balance) {
  return {
    deposit(amount) { balance += amount; return balance; },
    balance() { return balance; },     // there is no way to set balance directly
  };
}

// debounce: wait until the user stops typing
function debounce(fn, ms) {
  let timer;                         // remembered between calls
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}
const onSearch = debounce((text) => console.log("search", text), 300);

// memoisation: remember past results
function memoize(fn) {
  const cache = new Map();
  return (arg) => cache.has(arg) ? cache.get(arg) : (cache.set(arg, fn(arg)), cache.get(arg));
}

Event handlers, setTimeout callbacks, fetch(...).then(...) callbacks and React hooks (useState, useEffect) all rely on closures capturing variables.

The classic loop bug

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// prints 3, 3, 3

var i is one variable shared by the whole function. By the time the callbacks run, the loop has finished and i is 3. With let, each iteration gets its own i, and each callback closes over a different one:

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// prints 0, 1, 2

(Before let, people wrapped the body in an immediately invoked function to create a new scope per iteration.) This question is a favourite in interviews.

Closures and memory

A closure keeps its captured variables alive as long as the function exists. That is the point, but it can also keep large objects in memory (an event listener that captures a big array and is never removed), causing memory leaks. Remove event listeners when done (removeEventListener, the AbortController signal option, effect cleanup in React), and do not capture more than you need.

IIFE and modules

An immediately invoked function expression creates a private scope: (function () { const secret = 1; })();. Today ES modules do this for you: every module has its own scope, and only what you export is visible (the modules lesson), so IIFEs are rare.

Common mistakes

  • Using var in loops with asynchronous callbacks.
  • Accidental globals from missing declarations.
  • Using a let or const before its declaration (the TDZ error).
  • Expecting function expressions to be hoisted like declarations.
  • Capturing large objects in long-lived callbacks and leaking memory.
  • Shadowing a variable and editing the wrong one.

Try it yourself

  1. Predict the output of the var loop and of the let loop, then run both.
  2. Write makeCounter with increment, decrement and value methods, with the count private.
  3. Write debounce and use it on an input event so a search runs only 300 ms after the last keystroke.
  4. Show the TDZ error for let and the undefined result for var.
  5. Write a once(fn) function that runs fn only the first time it is called.

Check yourself

What is the difference between function scope and block scope?

var is scoped to the whole function, ignoring blocks; let and const are scoped to the nearest block ({ }).

What is the temporal dead zone?

The period from the start of a block until a let or const variable is declared, during which accessing it throws a ReferenceError.

What is a closure?

A function bundled with references to the variables of the scope where it was created, so it can use them later, even after that scope has finished.

Why does the var loop with setTimeout print the same number each time?

All callbacks share one function-scoped variable i, which has reached its final value when they run; let creates a new binding per iteration.

Interview questions

Explain closures with an example.

A closure lets an inner function use variables of its outer function after the outer function returned. For example, makeCounter returns a function that increments a private count; each call to makeCounter creates an independent counter.

What is hoisting?

JavaScript registers declarations before executing code: function declarations are fully available, var is hoisted as undefined, and let and const are hoisted but in the temporal dead zone until their declaration runs.

How do closures relate to memory leaks?

A closure keeps captured variables alive; a long-lived callback, such as an unremoved event listener, can keep large objects reachable and prevent them from being garbage collected.

Summary

  • Scope is global, function or block; let and const are block-scoped; the scope chain looks outward.
  • Function declarations hoist fully, var hoists as undefined, let and const have a temporal dead zone.
  • Closures give functions memory of their defining scope: counters, factories, debounce, private state.
  • Use let in loops, avoid accidental globals, and clean up long-lived callbacks.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.