What is the difference between var and let in scope chain questions?
var is function-scoped and leaks out of blocks; let and const are block-scoped. var is hoisted with undefined; let and const are hoisted but in the TDZ. This difference changes the output of many interview questions.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Scope Chain Interview Questions in JavaScript
Identify where each function was written (lexical scope), walk the scope chain from the current scope up to global, account for hoisting and shadowing, and remember that the chain does not change based on where the function is called.
Because JavaScript is lexically scoped. The scope chain is determined by where the function was written, not where it is called. The caller's variables are not in the function's scope chain.
var shadowing plus hoisting. An inner var with the same name as an outer variable is hoisted with undefined, so a read before the assignment line sees undefined instead of the outer value.
Still have questions?
Browse all our FAQs or reach out to our support team
