FresherTechnicalJavaScript
What is the difference between var, let and const?
Try answering first
Model answer
The three keywords differ in scope, hoisting and reassignment.
varis function-scoped, hoisted and initialized withundefined, and can be redeclared.letis block-scoped. It is hoisted but sits in the temporal dead zone until its declaration, so reading it earlier throws aReferenceError.constis block-scoped likelet, but the binding cannot be reassigned. An object held by aconstcan still be mutated.
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i))
// 3 3 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j))
// 0 1 2
In modern code, default to const and use let only when a value must change.
Key points
- var is function-scoped; let and const are block-scoped
- let and const live in the temporal dead zone before their declaration
- const prevents reassignment, not mutation
- Prefer const by default, let when needed
Likely follow-ups
- Why does the var loop print 3 3 3?
- How can you make an object truly immutable?
Common mistakes
- Saying let and const are not hoisted at all
- Believing const makes objects and arrays immutable