Scope & var/let/const (the TDZ)
Published by Brayan K
Scope answers one question: where can I see this variable? Getting it right is the difference between a clean program and one full of names that leak, clash, or mysteriously hold the wrong value.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Draw the boundary around each declaration
Scope describes where a name resolves to a particular binding. Start with the enclosing function or block, then follow the surrounding scopes outwards. A local declaration does not become visible to code outside its boundary merely because that code runs afterwards.
function packLabel(quantity) {
// This binding belongs to this call of packLabel.
const label = "Pack of " + quantity;
return label;
}
const result = packLabel(3);
console.log(result);
// ✅ Expected output:
// Pack of 3The caller receives the returned value through result. It does not receive access to the function-local label binding. Returning data is an explicit way to communicate across the boundary. Functions owns the call and return contract.
function createCode() {
const secretCode = "A17";
return secretCode;
}
console.log(createCode());
console.log(secretCode);
// ✅ Expected output:
// A17
// ✅ Expected error:
// ReferenceError: secretCode is not definedLet and const stay inside their block
A block statement creates a scope for let and const. The braces of an if body can therefore keep a temporary name local to that branch. If later code needs the result, declare a result binding in the enclosing scope and assign to it inside the branch.
if (true) {
const branchLabel = "packed";
console.log(branchLabel);
}
console.log(branchLabel);
// ✅ Expected output:
// packed
// ✅ Expected error:
// ReferenceError: branchLabel is not definedconst quantity = 3;
let message;
if (quantity > 0) {
const label = "packed";
message = label + " " + quantity;
} else {
message = "empty";
}
console.log(message);
// ✅ Expected output:
// packed 3Message is declared outside the branch and receives a value on either path. Label is a temporary detail of the positive-quantity path. An object literal also uses braces, but those braces describe an object rather than creating a block scope for declarations.
Var in an ordinary branch belongs to its containing function
Within a function, var is not confined by an ordinary if or loop block. A var declared in that branch is the function binding, including when another var declaration with the same name already appears in that function. This is one reason an apparently local change can alter a value used afterwards.
function inspectStatus() {
var status = "waiting";
if (true) {
var status = "packed";
console.log("inside", status);
}
console.log("after", status);
}
inspectStatus();
// ✅ Expected output:
// inside packed
// after packedfunction inspectStatus() {
let status = "waiting";
if (true) {
let status = "packed";
console.log("inside", status);
}
console.log("after", status);
}
inspectStatus();
// ✅ Expected output:
// inside packed
// after waitingThis comparison concerns ordinary blocks inside a function. Top-level module boundaries and class static initialization have additional rules; avoid turning it into the blanket claim that var has no other boundaries. JavaScript Modules: ES6 Imports, Exports, Bundling owns module scope.
Shadowing and reassignment change different things
A new declaration in an inner scope can hide an outer binding with the same name. That is shadowing: there are two bindings. An assignment without a new declaration instead updates the binding found by name lookup, provided it allows reassignment.
let label = "outer";
{
const label = "inner";
console.log(label);
}
console.log(label);
{
label = "updated";
}
console.log(label);
// ✅ Expected output:
// inner
// outer
// updatedWhen reading a larger function, circle declarations separately from assignments. Repeated spelling does not prove that two statements use the same binding. Use distinct names when shadowing would make the relationship harder to see.
function leftLabel() {
const label = "left";
return label;
}
function rightLabel() {
const label = "right";
return label;
}
console.log(leftLabel());
console.log(rightLabel());
// ✅ Expected output:
// left
// rightLook outwards from the function definition, not its caller
JavaScript uses lexical scope: the surrounding source structure determines where a function looks for a name. A caller does not lend its own local bindings to the function it calls. Follow the nesting in the source rather than the call stack.
const label = "catalogue";
function readLabel() {
return label;
}
function makeRequest() {
const label = "request";
console.log(label);
return readLabel();
}
console.log(makeRequest());
// ✅ Expected output:
// request
// catalogueReadLabel was defined outside makeRequest, so its surrounding label is the catalogue binding. It does not search the caller for a convenient same-named variable. Closures and Scope owns how that access can remain available after a surrounding function returns.
A shadowed outer value is not a fallback during initialization
An inner lexical declaration reserves its name for that scope even before initialization. An early read therefore targets the inner binding; it does not fall back to the initialized outer one. Hoisting owns the full initialization timeline and typeof behaviour.
const label = "outer";
{
console.log(label);
const label = "inner";
}
// ✅ Expected error:
// ReferenceError: Cannot access 'label' before initializationTo fix this mistake, initialize the intended inner value before reading it or choose a different name when you mean to read the outer value. Moving the read around without identifying its binding can hide the real problem.
A loop can share one counter or create a binding per iteration
Deferred callbacks read their bindings when called. The examples store functions and call them after the loop, so there are no timers or scheduling assumptions. With var, all callbacks refer to the same counter binding, which the loop has already finished updating.
const callbacks = [];
for (var index = 0; index < 3; index += 1) {
callbacks.push(() => index);
}
for (const callback of callbacks) {
console.log(callback());
}
// ✅ Expected output:
// 3
// 3
// 3const callbacks = [];
for (let index = 0; index < 3; index += 1) {
callbacks.push(() => index);
}
for (const callback of callbacks) {
console.log(callback());
}
// ✅ Expected output:
// 0
// 1
// 2The let version creates per-iteration bindings; it does not make every closure a frozen snapshot of every value it uses. Loops & Iteration owns the loop stages, while Closures and Scope owns the wider behaviour of retained bindings.
Choose the declaration for the binding you intend
Use const for a binding that will not be reassigned, and let for one that will. Both obey block scope. Const does not freeze an object; Variables and Data Types owns that binding-versus-mutation distinction.
Top-level names are also affected by whether code is a classic script, a module or a function wrapper such as an editor. Do not use a console experiment with a global property as proof that every file has the same scope. Keep working names local and pass or return data across boundaries.
function countItems(quantity) {
let count = 0;
for (let index = 0; index < quantity; index += 1) {
count += 1;
}
return count;
}
console.log(countItems(2));
console.log(countItems(1));
// ✅ Expected output:
// 2
// 1Complete a loop whose callbacks keep separate counters
Fill the declaration blank with the keyword that gives each loop iteration a separate counter binding. Then call the stored callbacks after the loop. The literal hint identifies the one change responsible for the different result.
const callbacks = [];
for (___ index = 0; index < 3; index += 1) { // 👉 replace ___ with let
callbacks.push(() => index);
}
for (const callback of callbacks) {
console.log(callback());
}
// ✅ Expected output:
// 0
// 1
// 2Prepare a message without replacing the catalogue label
Keep an outer label equal to "catalogue". Write prepareMessage(quantity) with a result named message, initially "empty". In the positive-quantity branch, declare a block-local label equal to "packed" and assign message from that label and the quantity. Return message, then print the results for quantities three and zero and the unchanged outer label.
const label = "catalogue";
function prepareMessage(quantity) {
let message = "empty";
if (quantity > 0) {
const label = "packed";
message = label + " " + quantity;
}
return message;
}
console.log(prepareMessage(3));
console.log(prepareMessage(0));
console.log(label);
// ✅ Expected output:
// packed 3
// empty
// catalogueMessage is the deliberate output of the function. The inner label is a separate binding used only to build it, so it cannot reassign the catalogue label.
References: MDN covers variable scope, let bindings, and var boundaries.
Practice quiz
What does this complete program print? let value = 1; { let value = 2; console.log(value); } console.log(value);
- 2 1
- 2 2
- 1 1
- 1 2
Answer: 2 1. The inner declaration creates a separate binding and leaves the outer one unchanged.
What does this complete program print? let value = 1; { value = 2; } console.log(value);
- 1
- 2
- undefined
- ReferenceError: value is not defined
Answer: 2. There is no new declaration in the block; the assignment updates the outer let binding.
What does this complete program print? function inspect() { var value = 1; if (true) { var value = 2; } return value; } console.log(inspect());
- 1
- undefined
- 2
- ReferenceError: value is not defined
Answer: 2. Both var declarations refer to the same binding in the containing function.
What does this complete program print? const label = "outer"; function read() { return label; } function caller() { const label = "caller"; return read(); } console.log(caller());
- caller
- undefined
- ReferenceError: label is not defined
- outer
Answer: outer. The function uses its lexical surrounding scope, not the local bindings of its caller.
What does this complete program print? const tasks = []; for (var i = 0; i < 2; i++) tasks.push(() => i); console.log(tasks[0](), tasks[1]());
- 2 2
- 0 1
- 1 2
- 0 0
Answer: 2 2. Both callbacks read the shared var counter after it has reached its final value.
What does this complete program print? const tasks = []; for (let i = 0; i < 2; i++) tasks.push(() => i); console.log(tasks[0](), tasks[1]());
- 2 2
- 0 1
- 1 2
- 0 0
Answer: 0 1. Each iteration has its own let binding for the stored callback to read.
Which error ends this program? const value = "outer"; { console.log(value); const value = "inner"; }
- ReferenceError: value is not defined
- TypeError: Assignment to constant variable.
- ReferenceError: Cannot access 'value' before initialization
- SyntaxError: Identifier 'value' has already been declared
Answer: ReferenceError: Cannot access 'value' before initialization. The inner declaration shadows the outer binding throughout the block; the early read reaches its temporal dead zone.
What does this complete program print? function count() { let value = 0; value += 1; return value; } console.log(count(), count());
- 1 2
- 2 2
- 0 0
- 1 1
Answer: 1 1. Each call starts with a fresh local binding initialized to zero.
Continue this course
- Previous: Hoisting
- Next: The this Keyword — How this is determined, and call / apply / bind
- Quick reference: JavaScript cheat sheet