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.
var vs let vs const — scoping differences
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.
window in browsers (for
var).
{ } — like inside
if, for, or any block. Only accessible within that block.
var ignores block scope.
type="module" scripts)
are scoped to the file. Nothing leaks to the global scope unless explicitly exported.
// ── 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-scopedvar 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) |
|
|
|
| let | Block |
|
|
|
|
| const | Block |
|
|
|
|
// ── 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";
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.
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();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.
// ── 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 countPractical 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.
Map —
only compute once per unique input.// ── 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.
// ── ❌ 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)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.
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.
// ── ❌ 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 capturevar print?
for(var i=0;i<3;i++) setTimeout(()=>console.log(i),0)
- Scope is the set of variables accessible at a given point in code. JS has four scopes: global, function, block (ES6), and module.
varis function-scoped and hoisted asundefined— it ignores block scope, leaking out ofifandforblocks.letandconstare 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
ReferenceErroris 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
varis used in a loop with async callbacks — all callbacks share a singlei. Fix it withlet(creates a new binding per iteration), an IIFE, or.bind(). - Use
constby default,letwhen re-assignment is needed, and never usevarin modern JavaScript.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.