Fundamentalsbeginner

var vs let vs const

How the three declaration keywords differ in scope, hoisting behavior, and mutability.

JavaScript shipped with only var for its first two decades, and ES6 added let and const specifically to fix problems that var caused in everyday code. Interviewers ask about this trio constantly because it is the fastest way to check whether you understand scope, hoisting, and the difference between rebinding a variable and mutating the value it holds.

Think of `var` as a shout that echoes through the whole building (function), while `let` and `const` are a whisper that only the people in the same room (block) can hear.

Key Concepts

1
var is function-scoped (or globally scoped if declared outside a function), meaning it ignores block boundaries like if statements and for loops entirely. It is also hoisted to the top of its scope and initialized with undefined, so referencing it before the declaration line does not throw, it just silently returns undefined. let and const are block-scoped, meaning they only exist inside the nearest {}, and they are hoisted too but land in a temporal dead zone where accessing them before the declaration throws a ReferenceError instead of returning undefined.
varifforundefinedlet
2
The difference between let and const is not about immutability of data but about immutability of the binding. A const cannot be reassigned to point at a new value, but if that value is an object or array, its contents can still be mutated freely. This trips up plenty of developers who expect const to make an object deeply frozen when it only locks the variable reference.
letconst
3
In modern codebases the convention is to default to const, switch to let only when a variable genuinely needs reassignment, and avoid var altogether. This isn't just a style preference: block scoping prevents an entire category of bugs where loop variables leak out of for loops or get accidentally shared across closures.
constletvarfor