Block scope and shadowing
A scope is the part of a program where a name can be read or written. In JavaScript a function creates one, and so does every pair of braces: the body of an if, a for loop, a bare block or a try block. A let or const declared inside belongs to that block and stops existing at the closing brace.
Because blocks nest, a name may be declared twice, and the inner declaration wins for the lines inside it. That is shadowing, and the language allows it because a short name inside a function should not have to be invented around a name in the file above. It also produces bugs that are hard to see, so the last section of this lesson is about when not to use it.
A block is a scope
The program below declares status twice: once in the file and once inside a bare pair of braces. The inner declaration is a new binding, so the two writes reach two values. A const inside an if block behaves in the same way, and the name is gone after the closing brace.
const ready = true;
let status = 'outside';
{
let status = 'inside';
console.log('inner:', status);
}
console.log('outer:', status);
if (ready) {
const total = 3;
console.log('in the if:', total);
}
console.log('total outside:', typeof total);
node blocks.mjs
inner: inside
outer: outside
in the if: 3
total outside: undefined
The two status lines print different values because they read different bindings, and the outer one never changed. The last line is typeof on a name that does not exist at that point, which answers "undefined" instead of throwing. Reading total directly would throw a ReferenceError, as the lesson on variables shows for the temporal dead zone.
Shadowing
Shadowing is the same mechanism used on purpose: the inner block declares a name that the outer scope already has, and from that line to the end of the block the name means the inner binding. The outer binding is not hidden for ever; it comes back when the block ends. The program below shadows a file name in a function and in a block, and reads the outer name after each.
const name = 'Ada';
let count = 0;
function greet() {
const name = 'Grace';
count += 1;
return `Hello, ${name}`;
}
console.log(greet());
console.log('outer name:', name);
console.log('count:', count);
{
const name = 'Katherine';
console.log('block name:', name);
}
console.log('outer name again:', name);
node shadowing.mjs
Hello, Grace
outer name: Ada
count: 1
block name: Katherine
outer name again: Ada
The function printed its own name and left the outer one alone, and the block did the same. Note that count was not shadowed: the function writes the outer binding and the increase is visible outside, which is the behaviour the next lesson calls a closure.
One binding per pass
A for loop with let declares a new binding for each pass, and a callback created in that pass keeps that binding. With var there is one binding for the whole loop, and every callback reads its final value. The program collects a function from each pass of both kinds of loop and calls them at the end.
const withLet = [];
const withVar = [];
for (let step = 0; step < 3; step += 1) {
withLet.push(() => step);
}
for (var counter = 0; counter < 3; counter += 1) {
withVar.push(() => counter);
}
console.log('let:', withLet.map((fn) => fn()).join(', '));
console.log('var:', withVar.map((fn) => fn()).join(', '));
node loopscope.mjs
let: 0, 1, 2
var: 3, 3, 3
Three callbacks from the let loop and three answers, because each pass got its own binding. The var loop has one binding that ended the loop at 3, so all three callbacks read 3. This is the bug that made let worth adding to the language, and the next lesson explains why a callback can read a variable of a loop that has finished at all.
Why shadowing confuses readers
A shadowed name is legal, and a reader who scans a long function sees one name where the program uses two. The bug it causes is quiet: a line inside the block writes what looks like the outer variable, and the value after the block is the old one. Tests that call the function with one input rarely notice, because the mistake shows only in the interaction between the two bindings.
Two habits remove most of it. Give a new value a new name, so that total and lineTotal are different words rather than one word twice. And keep the outer scope small: a name declared in the function that needs it cannot be shadowed by accident three screens away. Short loop counters such as index are the usual exception, and even they are cheaper to rename than to debug.
Exercises
- Remove the let in front of status inside the block of blocks.mjs. Which output changes, and why is the program no longer shadowing?
- Print count inside greet in shadowing.mjs before the increase. What does the function see, and what does the outer line print afterwards?
- Change let step to var step in loopscope.mjs and run it. What do the two lines print now?
- Wrap the console.log(greet()) line in a block that declares its own const name. Which name does the call use, and which one does the next line read?
- Declare const value = 1; in a function and again inside an if in that function, then print both after the if. Which line throws, and which error is it?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Where does a
letbinding declared inside anifblock exist?Answer
In the block where it is declared
let and const are block-scoped, so the closing brace of the if ends the name.
-
What does this program print?
const name = "Ada"; { const name = "Grace"; console.log(name); } console.log(name);Answer
Grace / Ada
The inner declaration shadows the outer one inside the block, and the outer binding is back after it.
-
What does this program print?
{ let inside = 1; console.log(inside); } console.log(typeof inside);Answer
1 / undefined
The binding ends with the block, and typeof answers undefined for a name that is not there.
-
What does this program print?
const fns = []; for (let i = 0; i < 2; i += 1) { fns.push(() => i); } console.log(fns.map((fn) => fn()).join(","));Answer
0,1
Each pass of a let loop has its own binding, so the two callbacks read 0 and 1.
-
What does this program print?
let total = 1; { let total = 2; total += 1; } console.log(total);Answer
1
The increase reached the inner binding only, and the outer total was never touched.
-
Why does a
varloop counter give every callback the same value?Answer
Because var creates one binding for the whole function
A var binding belongs to the function, so all the callbacks read the one value it ends with.
-
What does
typeofreport for a name declared withletin a block that has ended?Answer
"undefined"
typeof never throws for an unknown name and answers undefined, while a plain read would throw.
-
Which of these is the usual reason to avoid shadowing?
Answer
A reader sees one name where the program uses two
The code stays legal, and the cost is that a human has to track two bindings with one word.
-
What does this program print?
const value = 1; function read() { const value = 2; return value; } console.log(read(), value);Answer
2 1
The function returns its own shadowing binding, and the file binding keeps the value 1.
-
A block declares
let totaland an outer scope haslet total. What happens at the declaration?Answer
A new binding is created for the block
Declaring a name in an inner block is legal and creates a new binding that shadows the outer one.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev