Block Scope and Shadowing
Curly braces create blocks, but only let and const respect them. var leaks right through, which is why shadowing with var can cause surprising bugs.
let and const are block-scoped: they live and die within curly braces. var is function-scoped and ignores blocks. Shadowing with let is safe; shadowing with var overwrites.
EXERCISE
1What Is a Block?
Curly braces {} create a block. It is a way to group multiple statements together. And for let and const, blocks create their own private scope.
A block is any code wrapped in curly braces. The body of an if, the body of a loop, or a bare pair of braces standing on its own are all blocks. Whether a block creates a scope depends entirely on which keyword you used to declare the variable, and that inconsistency is the source of a whole category of bug.
{
var a = 10;
let b = 20;
const c = 30;
}
console.log(a); // 10
console.log(b); // ReferenceError: b is not defined
console.log(c); // ReferenceError: c is not defined
let and const are scoped to the block. var is not scoped to blocks at all: it belongs to the nearest enclosing function, or to the top level if there is no function. So a was never really inside those braces as far as the engine is concerned.
The same difference inside an if, which is where you will actually meet it:
if (true) {
var inside = "visible later";
let alsoInside = "not visible later";
}
console.log(inside); // "visible later"
console.log(alsoInside); // ReferenceError
Nothing about the if matters here. The braces are a block, var ignores blocks, and the variable outlives the statement that appeared to contain it.
Loops make the consequence concrete:
for (var i = 0; i < 3; i++) {
// ...
}
console.log(i); // 3
for (let j = 0; j < 3; j++) {
// ...
}
console.log(j); // ReferenceError: j is not defined
After the first loop, i is still in scope holding 3, which is the value that ended the loop. That leaked counter is a real hazard in long functions: a second loop reusing the name i is not creating a fresh variable, it is reusing the same one.
The practical takeaway is that let and const behave the way the braces suggest, and var does not. If you write only let and const, block scope is exactly what it looks like and this lesson stops applying.
One more consequence is worth knowing before you meet it in a loop with a callback:
for (var i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i);
}, 0);
}
// 3, 3, 3
All three callbacks print 3, because there is only one i and by the time they run the loop has finished with it. Swap var for let and each iteration gets its own binding, so the output becomes 0, 1, 2. That single-keyword difference is one of the most-asked interview questions in , and Unit 5 returns to it properly.
EXERCISE
2Shadowing: When Inner Hides Outer
When a variable inside a block or function has the same name as one outside, the inner variable shadows (hides) the outer one within that scope.
Shadowing is declaring a variable with the same name as one in an outer scope. With let and const the two are separate bindings that merely share a name. With var they can turn out to be the same binding, and the outer value is destroyed.
var inside a block is not a new variable:
var color = "blue";
{
var color = "red";
console.log(color); // "red"
}
console.log(color); // "red"
The last line is the one that matters. The outer color is now "red", because var does not recognise the block, so the inner declaration referred to the same variable the whole time. Nothing was shadowed; something was overwritten.
let behaves the way the braces look:
let color = "blue";
{
let color = "red";
console.log(color); // "red"
}
console.log(color); // "blue"
Two bindings, two scopes. The inner one exists only within the braces, and the outer one is untouched when the block ends. const behaves identically.
The difference is not academic. Consider a block that was added later, inside a function that already had a variable of that name:
function applyDiscount(prices) {
var total = 0;
if (prices.length > 3) {
var total = prices.length; // intended as a local counter
}
return total;
}
The author of the if block believed they were creating a counter. They were reassigning the running total, and the function now returns the wrong number in exactly the case the block was added to handle. Written with let, the inner declaration would have been genuinely separate, and written with let for both it would have been a syntax error, which is better still.
Pro Tip: When a value changes and you cannot find the assignment responsible, search the function for a second declaration of the same name. With
varthe duplicate is legal, silent, and the same variable.
The const case behaves the same way as let, which is worth confirming rather than assuming:
const rate = 0.2;
{
const rate = 0.5;
console.log(rate); // 0.5
}
console.log(rate); // 0.2
Declaring a const inside a block does not conflict with a const of the same name outside it, because the two live in different scopes. const prevents reassignment of a binding; it does not reserve the name across every scope in the file.
EXERCISE
3Illegal Shadowing
There is one rule you cannot break: you cannot shadow a let variable with a var in the same scope. JavaScript will refuse to run your code.
Some shadowing combinations are rejected outright. The rule sounds arbitrary until you apply what you already know about which keyword respects blocks.
Shadowing a let with a var in a block is a syntax error:
let name = "Global";
{
var name = "Block"; // SyntaxError: Identifier 'name' has already been declared
}
Work out why from the rule rather than memorising it. var is not scoped to the block, so it is trying to declare name in the outer scope. There is already a let name there. Two declarations of the same name in one scope, where one of them is let, is a duplicate, and duplicates are rejected before the file runs.
The same two keywords are fine when a function sits between them:
let name = "Global";
function test() {
var name = "Function";
console.log(name); // "Function"
}
test();
console.log(name); // "Global"
Nothing changed about var except that it now has a function to belong to. It declares name inside test, which is a different scope from the outer let, so there is no collision at all.
let shadowing let is always allowed, because block scope is real for both:
let count = 10;
{
let count = 20;
console.log(count); // 20
}
console.log(count); // 10
And let shadowing a var works for the same reason:
var total = 10;
{
let total = 20;
console.log(total); // 20
}
console.log(total); // 10
The inner let creates a binding scoped to the braces. The outer var is untouched, because nothing tried to redeclare it in its own scope.
Every one of these outcomes follows from a single fact: let and const are scoped to the block, var is scoped to the function. You do not need five rules, you need that one and the willingness to ask which scope a declaration actually lands in.
Pro Tip: A
SyntaxErrorof this kind stops the entire file from running, including the lines above it. If a module appears to do nothing at all, a duplicate declaration is worth checking before anything else.
