QuestionsJavaScript

var vs let/const, hoisting, and the TDZ

Scope & HoistingEasyJavaScript

Explain hoisting. What is the difference between var, let, and const, and what is the temporal dead zone?

What it tests

Understanding of hoisting mechanics and block scope — a very common warm-up that seeds closure-in-loop bugs.

Approach & answer

Declarations are 'hoisted': the engine registers them before running the code. A var is function-scoped and initialized to undefined at hoist time, so reading it before its assignment gives undefined (not an error). let and const are block-scoped and also hoisted, but they stay uninitialized in the temporal dead zone (TDZ) from the top of the block until the declaration line — touching them there throws a ReferenceError, which catches typos and use-before-init. const additionally forbids reassignment of the binding (the referenced object can still mutate). Function declarations are fully hoisted and callable before their line; function expressions and arrows follow their variable's rules. Classic trap: var i in a for loop is shared across all iterations, so async callbacks all see the final value — let creates a fresh binding per iteration and fixes it. Prefer const by default, let when you must reassign, and avoid var.

Use this technique when

Any 'what does this print' question, closure-in-loop bugs, or reasoning about block scope.

References

js