What is accidental shadowing in JavaScript?
When an inner var declaration has the same name as an outer variable. The inner one is hoisted with undefined, so reads before the assignment line see undefined, not the outer value. Use let with distinct names to avoid it.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Hoisting Pitfalls and Bugs to Avoid in JavaScript
Using a var before assignment (returns undefined or NaN), var leaking out of loops, calling a function expression before assignment (TypeError), accidental shadowing, and TDZ surprises with let and const.
Use const by default and let when you must reassign, avoid var, declare variables at the top of their scope, use const for function expressions, and enable strict mode to catch silent issues.
Because var is function-scoped, not block-scoped. The loop variable exists in the enclosing function (or global scope). Using let makes the variable block-scoped and confined to the loop.
Still have questions?
Browse all our FAQs or reach out to our support team
