Variable shadowing
Learn to shadow an outer variable by declaring one with the same name in an inner scope.
Variable shadowing
When you re-declare a variable with the same name in an inner scope, you shadow the outer one. The inner scope now sees the new variable; the outer one stays untouched.
For example, if you write let score = 10; outside and then let score = 50; inside a function, score is 50 inside the function. When the function ends, the outer 10 returns. This is also known as name reuse.
Shadowing pitfalls
Shadowing can be useful; but used carelessly it makes the code harder to read. When the same name appears both outside and inside, the reader must trace the scope carefully to know which variable is in use.
Mixing var and let with the same name can lead to surprising results. Giving the inner variable a different, descriptive name is often safer. If you do shadow, keep it short and note the reason in a comment.
Exercise Shadow the outer variable
Declare let score = 10 outside. Write a function called addBonus() that declares let score = 50 inside, shadowing the outer score, and returns score + 5. Outside, first log the function result with console.log(addBonus()), then log the outer score with console.log(score).
Show example solution
let score = 10;
function addBonus() {
let score = 50;
return score + 5;
}
console.log(addBonus());
console.log(score);
Test yourself
-
What does this code print?
let score = 10; function bonus() { let score = 50; return score; } console.log(bonus());- 10
- 60
- undefined
- 50
Show answer
50 — Correct. The bonus function returns the inner score.
-
Shadow in the inner scope
let score = 10; function bonus() { let ____ = 50; return score; }Show answer
let score = 10; function bonus() { let score = 50; return score; } -
Match the scenario to its result
- Outer score=10, inner score=50
- Inner reads 50
- Outer score=10, no inner
- Inner reads 10
- No inner, no outer score
- ReferenceError
- Function done, outer=10
- Still reads 10