JavaScript · Question 4 of 50

What is hoisting? What is the difference between var, let and const?

What they're checking

Scope rules, the temporal dead zone, and why let was added.

The answer

Before code runs, JavaScript registers every declaration in its scope. A var is registered and set to undefined, so reading it early gives undefined. let and const are registered too but not initialised: reading them before their line throws a ReferenceError. That gap is the temporal dead zone. Function declarations are hoisted whole, so you can call them above where they are written.

var is function-scoped; let and const are block-scoped. const stops re-assignment, not change: const list = [] followed by list.push(1) is fine.

console.log(a) // undefined
var a = 1
console.log(b) // ReferenceError: the temporal dead zone
let b = 2
greet()        // works: function declarations are hoisted whole
function greet() {}

The picture

           hoisted   read before its line   scope
var        yes       undefined              function
let        yes       ReferenceError (TDZ)   block
const      yes       ReferenceError (TDZ)   block, no re-assign
function   whole     callable               function / block
The follow-up they'll ask

Is a const object immutable?

Show the answer

No. The name cannot point to something else, but the object itself can change. Object.freeze makes a shallow freeze.

Your progress stays on this device.