JavaScript Shadowing Versus Reassignment
Quick answer
Shadowing occurs when an inner scope declares a binding with the same name as an outer one. Within that inner scope the name resolves to the inner binding. Reassignment changes a binding that already exists.
How it works
Name lookup stops at the first matching lexical binding. It does not search for the nearest initialized binding. If the inner binding exists but is still uninitialized, the read fails instead of falling back to the outer value. A parameter can also shadow an outer name; use distinct names when the difference is important.
let price = 10;{ let price = 7; price = 8; console.log(price);}console.log(price);Expected output in Node.js:
810Only the inner price changed.
Expected output in Node.js:
9No inner score exists.
Common mistakes
Shadowing is legal across separate scopes, but duplicate let declarations in one scope are not. Accidentally declaring a new local instead of updating the existing one can leave the outer result unchanged.
Practice
Predict both outputs before running the examples. Change the inner name in the first example to discountPrice and update its uses.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Shadowing Versus Reassignment — Knowledge Check
Apply the taught concept and reason about the result.
What does let n = 3; { let n = 9; console.log(n); } console.log(n); print?
What does let n = 3; { n = 8; } console.log(n); print?
Which situation is shadowing?
Can a function parameter shadow an enclosing binding?
What if the nearest matching lexical binding is in its TDZ?