When a variable in an inner scope has the same name as a variable in an outer scope. The inner one shadows (hides) the outer one. The engine finds the inner first and stops searching the scope chain. The outer is unaffected but hidden.
Variable Shadowing in JavaScript Explained
What is variable shadowing in JavaScript?
The answer
More FAQs in Variable Shadowing in JavaScript Explained
Because the inner var is hoisted to the top of the function with undefined, shadowing the outer immediately. A read before the assignment line sees undefined, not the outer value.
No. It throws SyntaxError: Identifier 'x' has already been declared. var ignores block boundaries, so it would leak and conflict. Shadowing a var with a let is fine, but not the reverse.
No. The outer variable is unchanged. Shadowing only hides it within the inner scope. Once the inner scope ends, the outer variable is visible again with its original value.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.