Tutorials JavaScript Scope & Closures
Ch 24 / 78
Chapter 24 Intermediate 10 min read JavaScript

Scope & Closures

Scope determines which variables are accessible at any given point in your code. Closures are functions that remember the variables from the scope in which they were created — even after that outer function has returned. Together, scope and closures are the engine behind private state, factory functions, memoization, event handlers, and many of JavaScript's most powerful patterns.

What you'll learn
The 4 types of scope: global, function, block, and module
How the scope chain resolves variable look-ups
var vs let vs const — scoping differences
What a closure is and how it captures variables
Practical closure patterns: counters, private state, factories
The classic loop closure bug and how to fix it

What Is Scope?

Scope is the set of rules that governs where a variable can be read or written. When JavaScript looks up a variable name, it searches the current scope first, then each surrounding (outer) scope, all the way up to the global scope. If it still can't find it, it throws a ReferenceError.

Global Scope
Variables declared outside any function or block. Accessible everywhere in the program. Attaches to window in browsers (for var).
var let const
Function Scope
Variables declared inside a function. Only accessible within that function and any nested functions inside it.
var let const
Block Scope
Variables declared inside { } — like inside if, for, or any block. Only accessible within that block. var ignores block scope.
let const
Module Scope
Variables in ES modules (type="module" scripts) are scoped to the file. Nothing leaks to the global scope unless explicitly exported.
export import
🔍 Scope nesting — inner scopes see outer variables
🌍 Global Scope
appName version
⚙️ Function Scope — outer()
x appName ✓ inherited
🧱 Block / Inner Scope
y x ✓ inherited appName ✓ inherited
JavaScript — Scope in Action
// ── Global scope ─────────────────────────────────────────────
const appName = "MyApp"; // accessible everywhere

function outer() {
// ── Function scope ──────────────────────────────────────────
const x = 10;
console.log(appName); // ✅ "MyApp" — global is accessible here

function inner() {
// ── Nested function scope ──────────────────────────────────
const y = 20;
console.log(x); // ✅ 10 — outer's x is accessible
console.log(appName); // ✅ "MyApp" — global accessible
}
inner();
console.log(y); // ❌ ReferenceError — y is inside inner()
}
outer();
console.log(x); // ❌ ReferenceError — x is inside outer()

// ── Block scope: let and const ───────────────────────────────
if (true) {
let blockLet = "only inside";
const blockConst = "also only inside";
var blockVar = "leaks out!"; // var ignores blocks!
}
console.log(blockVar); // ✅ "leaks out!" — var is function-scoped
console.log(blockLet); // ❌ ReferenceError — let is block-scoped

var vs let vs const — Scoping Differences

All three keywords declare variables, but they differ significantly in scope, hoisting behaviour, and re-assignment rules. Understanding these differences is essential — var's function-scoped hoisting has caused countless real-world bugs that let and const were designed to prevent.

Keyword Scope Hoisted? Re-assignable? Re-declarable? Use today?
var Function / Global Yes (as undefined)
Yes
Yes
Avoid
let Block
TDZ error
Yes
No
Yes
const Block
TDZ error
No
No
Yes — prefer
JavaScript — var / let / const Scoping
// ── var: function-scoped, ignores blocks ───────────────────── 
function testVar() {
for (var i = 0; i < 3; i++) { /* loop block */ }
console.log(i); // 3 — var leaks out of the for block!
}

// ── let: block-scoped ────────────────────────────────────────
function testLet() {
for (let i = 0; i < 3; i++) { /* loop block */ }
console.log(i); // ❌ ReferenceError — i is only inside the for block
}

// ── const: block-scoped + can't be reassigned ────────────────
const PI = 3.14159;
PI = 3; // ❌ TypeError: Assignment to constant variable

// ⚠️ const with objects: binding is constant, NOT the contents
const user = { name: "Alice" };
user.name = "Bob"; // ✅ mutating a property is fine
user = {}; // ❌ TypeError — can't reassign the binding

// ── var hoisting (the dangerous part) ───────────────────────
console.log(hoisted); // undefined (hoisted as undefined — no error)
var hoisted = "value";

console.log(notHoisted); // ❌ ReferenceError (Temporal Dead Zone)
let notHoisted = "value";
Modern Best Practice
Use const by default. Switch to let only when you need to re-assign the variable (e.g. a loop counter or accumulator). Never use var in modern JavaScript — its function-scoped hoisting behaviour causes subtle, hard-to-find bugs.

The Scope Chain

When JavaScript looks up a variable, it follows the scope chain — it starts in the current execution context and walks up through each surrounding scope until it finds the variable or reaches the global scope. This lookup happens at runtime and is determined by where functions are written in the source code (lexical scope), not where they are called.

JavaScript — Scope Chain Lookup
const globalVar = "global"; // Level 1 — global

function level1() {
const l1Var = "level1"; // Level 2

function level2() {
const l2Var = "level2"; // Level 3

function level3() {
// ── Scope chain lookup order ──────────────────────────
console.log(l2Var); // ✅ "level2" — found in level2 scope
console.log(l1Var); // ✅ "level1" — found in level1 scope
console.log(globalVar);// ✅ "global" — found in global scope

// Shadowing: inner variable hides the outer one
const l1Var = "shadowed";
console.log(l1Var); // ✅ "shadowed" — local wins, outer is hidden
}
level3();
}
level2();
}
level1();

// ── Lexical scope: defined by WHERE it's written, not called ─
const lang = "JavaScript";

function printLang() {
console.log(lang); // uses lang from where it was DEFINED (global)
}

function caller() {
const lang = "Python"; // local lang — does NOT affect printLang
printLang(); // still logs "JavaScript" — lexical, not dynamic
}
caller();
Lexical (Static) Scope
JavaScript uses lexical scope — a function's scope is determined by where it is written in the source, not where it is called. This is why printLang() always logs "JavaScript" regardless of where it is called from. This property is what makes closures possible.

What Is a Closure?

A closure is a function that retains access to its lexical scope even when the function is executed outside that scope. In other words, an inner function closes over the variables of its outer function — those variables stay alive in memory as long as the inner function exists, even after the outer function has returned and its call stack frame is gone.

How a closure captures its environment
Outer Function
makeCounter() — returns and exits
let count = 0 ← captured in closure
↑ closes over
Closure
increment — the returned inner function
Remembers: count (from outer scope)
↓ invoked later
Execution
counter() — called after makeCounter() returned
count is still accessible and persistent → 1, 2, 3…
JavaScript — Your First Closure
// ── Step 1: outer function with a local variable ──────────────
function makeCounter() {
let count = 0; // local to makeCounter

// ── Step 2: inner function that references the outer variable
return function increment() {
count++; // reads AND updates the outer count
return count;
};
}

// ── Step 3: makeCounter returns and its frame is gone —
// ── but the inner function CLOSES OVER count, keeping it alive
const counter = makeCounter();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

// ── Each call to makeCounter creates a NEW, independent closure
const counterA = makeCounter();
const counterB = makeCounter();

counterA(); // 1
counterA(); // 2
counterB(); // 1 ← completely independent count

Practical Closure Patterns

Closures power many real-world JavaScript patterns. These are the most important ones you'll encounter in production code, interviews, and open-source libraries.

Private State
Hide a variable from the outside world — only the returned functions can access it.
Factory Functions
Generate specialised functions with pre-filled arguments captured in a closure.
Memoization
Cache expensive results in a closed-over Map — only compute once per unique input.
Partial Application
Pre-fill some arguments of a function and return a new one awaiting the rest.
Event Handlers
Callbacks capture data from the surrounding scope — no need for global variables.
Module Pattern
Use an IIFE + closure to create a public API while keeping internals private.
JavaScript — Closure Patterns in Practice
// ── 1. Private state ─────────────────────────────────────────
function createBankAccount(initialBalance) {
let balance = initialBalance; // private — can't be accessed directly
return {
deposit: (n) => { balance += n; return balance; },
withdraw: (n) => { balance = Math.max(0, balance - n); return balance; },
balance: () => balance,
};
}
const acc = createBankAccount(100);
acc.deposit(50); // 150
acc.withdraw(30); // 120
acc.balance(); // 120
// balance is 120 but no one outside can set it directly ✅

// ── 2. Factory function — multiplier ─────────────────────────
function multiplier(factor) {
return n => n * factor; // captures factor in closure
}
const double = multiplier(2);
const triple = multiplier(3);
const tenTimes = multiplier(10);
console.log(double(5)); // 10
console.log(triple(5)); // 15
console.log(tenTimes(7)); // 70

// ── 3. Memoization ───────────────────────────────────────────
function memoize(fn) {
const cache = new Map(); // closed over — persists between calls
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log("cache hit"); return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
};
}
const expensiveAdd = memoize((a, b) => a + b);
expensiveAdd(2, 3); // computed: 5
expensiveAdd(2, 3); // cache hit: 5

// ── 4. Module pattern (IIFE) ─────────────────────────────────
const ThemeManager = (() => {
let current = "dark"; // private
const themes = ["dark", "light", "system"];
return {
get: () => current,
set: (t) => { if (themes.includes(t)) current = t; },
toggle: () => { current = current === "dark" ? "light" : "dark"; },
};
})();
ThemeManager.get(); // "dark"
ThemeManager.toggle(); // switches to "light"

The Classic Loop Closure Bug

One of the most famous JavaScript interview questions involves closures inside loops. Using var in a loop creates a single shared variable — all closures capture the same reference, not a snapshot of the value at each iteration. This leads to a notorious bug where every callback logs the same final value.

JavaScript — Loop Closure Bug & 3 Fixes
// ── ❌ The Bug: var shares one binding across all iterations ──
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Logs: 3 3 3 — all callbacks share the same `i`

// ──────────────────────────────────────────────────────────────
// ✅ Fix 1: use let — creates a NEW binding per iteration
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Logs: 0 1 2 ✅

// ──────────────────────────────────────────────────────────────
// ✅ Fix 2: IIFE — capture i by value in a new function scope
for (var i = 0; i < 3; i++) {
((function(j) {
setTimeout(() => console.log(j), 100);
})(i));
}
// Logs: 0 1 2 ✅

// ──────────────────────────────────────────────────────────────
// ✅ Fix 3: bind — pass i as an argument snapshot
for (var i = 0; i < 3; i++) {
setTimeout(console.log.bind(null, i), 100);
}
// Logs: 0 1 2 ✅ (bind snapshots i at call time)
Why This Happens
var declares a single i variable shared across all loop iterations. All three callbacks close over the same binding. By the time they execute (100ms later), the loop has already finished and i is 3. let creates a fresh binding for each iteration, so each callback captures its own unique copy.

Try It — Live Editor

Experiment with scope and closures in the live playground below. Modify the counter, factory, and memoize examples to build your intuition.

Live Editor
✎ Editor
👁 Preview

Common Pitfalls & Best Practices

Scope and closures are powerful — but a few common mistakes can cause memory leaks, stale references, and hard-to-debug behaviour.

JavaScript — Pitfalls & Best Practices
// ── ❌ Pitfall 1: accidental global variable ──────────────────
function oops() {
leaked = "I'm global now!"; // no var/let/const — attaches to window
}
oops();
console.log(leaked); // "I'm global now!" — pollutes global scope
// ✅ Fix: always declare variables with const / let

// ── ❌ Pitfall 2: closure over stale reference ────────────────
function makeAdder(x) {
return y => x + y; // ✅ x is a parameter — stable per call
}
const add5 = makeAdder(5);
add5(3); // 8 — fine

// ── ❌ Pitfall 3: memory leak — closure keeps large object alive
function createHandler() {
const bigData = new Array(1000000).fill("x"); // large allocation
return () => bigData.length; // closure keeps bigData alive forever
}
// ✅ Fix: don't capture large data unnecessarily
function createHandlerFix() {
const bigData = new Array(1000000).fill("x");
const len = bigData.length; // only capture what you need
return () => len; // bigData is now eligible for GC
}

// ── ✅ Best practice: const by default, let when reassigning ─
// ✅ Use closures for private state instead of global variables
// ✅ Use let in for loops to get per-iteration bindings
// ✅ Be aware of what large objects your closures capture
Mental Model
Think of a closure as a backpack attached to every function. When a function is created, it packs into its backpack all the variables from the surrounding scope that it references. Wherever the function travels — even across async operations or callbacks — it always carries that backpack with it and can reach inside it at any time.
⚡
Free Resource
Download our JavaScript Cheat Sheet
Scope, closures, hoisting & execution context — one printable page.
Get Sheet
Quick Check
What is a closure in JavaScript?
Quick Check
What does the classic loop closure bug with var print? for(var i=0;i<3;i++) setTimeout(()=>console.log(i),0)
Quick Check
Which keyword(s) respect block scope?
Chapter Summary
  • Scope is the set of variables accessible at a given point in code. JS has four scopes: global, function, block (ES6), and module.
  • var is function-scoped and hoisted as undefined — it ignores block scope, leaking out of if and for blocks. let and const are block-scoped with Temporal Dead Zone protection.
  • The scope chain is the lookup path JavaScript follows when resolving a variable: current scope → outer scopes → global. If not found, a ReferenceError is thrown.
  • JavaScript uses lexical scope — a function's scope is determined by where it is written, not where it is called. This is the foundation of closures.
  • A closure is a function that retains access to the variables of its outer scope even after that outer function has returned. Each closure gets its own private copy of the captured variables.
  • Key closure patterns: private state, factory functions, memoization, partial application, and the module pattern.
  • The classic loop closure bug occurs when var is used in a loop with async callbacks — all callbacks share a single i. Fix it with let (creates a new binding per iteration), an IIFE, or .bind().
  • Use const by default, let when re-assignment is needed, and never use var in modern JavaScript.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel