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,letandconst - 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
letandconsthave block scope: they exist only inside the nearest{ }. The innercourseshadows the outer one, which is unchanged afterwards. Outside the block,lessonsdoes not exist, sotypeofreportsundefined. - Hoisting means declarations are processed before the code runs. A
functiondeclaration is hoisted completely, sosquare(4)works on a line above it. - A
vardeclaration is hoisted but its value is not:earlyexists from the start with the valueundefined. letandconstare hoisted too, but reading them before their line throws aReferenceError. The stretch of code before the declaration is called the temporal dead zone. This turns silent bugs into clear errors.- In the loops,
var iis one variable shared by every callback, so all three see its final value, 3.let jcreates 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
makeCounterreturns, its variablecountis 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:visitsandlikesnever affect each other. Nothing outside can readcountdirectly (visits.countisundefined), which gives true private state. - A function factory such as
makeDiscount(20)returns a small function that remembers its ownpercent. memoizekeeps aMapin its closure. The secondfastSquare(9)comes from the cache, so the slow function ran only twice for three calls.onceremembers whether it has already run. Setup code such as a database connection often uses this pattern.
Scope Rules at a Glance
| Declaration | Scope | Hoisted? | Use before the line | Re-declare? |
|---|---|---|---|---|
var | Function | Yes, as undefined | Gives undefined | Yes |
let | Block | Yes, but uninitialised | ReferenceError | No |
const | Block | Yes, but uninitialised | ReferenceError | No |
function f() {} | Function or block | Fully | Works | Avoid |
const f = () => {} | Block | Like const | ReferenceError | No |
Common Mistakes
- Using
varin loops with callbacks, so every callback sees the last value. Uselet. - Forgetting to declare a variable. In non-strict code,
total = 5silently creates a global; in strict mode it throws. - Expecting each closure to get a copy of a variable. Closures share the variable itself, so later changes are visible.
- 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
letandconstare block-scoped;varis function-scoped.- Function declarations are fully hoisted;
letandconsthave 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.
