Last reviewed
Correct answer: C. `let` has block scope, while `var` has function scope
Explanation
The difference is about which curly braces count. MDN states that "let declarations are scoped to blocks as well as functions", while for the older keyword "other block constructs, including block statements, try...catch, switch, headers of one of the for statements, do not create scopes for var, and variables declared with var inside such a block can continue to be referenced outside the block". A var written inside an if body or a for header therefore leaks into the whole surrounding function. Two consequences follow that you will actually meet. First, the classic loop bug: a for loop declared with var shares one binding across every iteration, so callbacks created inside it all read the final value, while let creates a fresh binding per iteration and each callback keeps its own. Second, "let declarations can only be accessed after the place of declaration is reached (see temporal dead zone)", so touching one too early throws a ReferenceError instead of quietly handing you undefined the way a hoisted var does. That noisy failure is the feature — it converts a silent wrong value into an error you can find.
Sources
“let declarations are scoped to blocks as well as functions.”
“other block constructs, including block statements, try...catch, switch, headers of one of the for statements, do not create scopes for var, and variables declared with var inside such a block can continue to be referenced outside the block”
“let declarations can only be accessed after the place of declaration is reached (see temporal dead zone). For this reason, let declarations are commonly regarded as non-hoisted.”
Practise 3 questions on this topic
Take JavaScript ES6 Features — Timed Test (3 questions) — scored instantly, explanation for every question, no login.