var, let, and const are used to declare variables in JavaScript, but they differ in scope, hoisting, and mutability.
1️⃣ var
- Scope: Function-scoped
- Hoisting: Yes, initialized with
undefined - Reassignable: Yes
- Redeclarable: Yes
function exampleVar() {
if (true) {
var x = 10;
}
console.log(x); // 10 → accessible outside block
}
exampleVar();
2️⃣ let
- Scope: Block-scoped
- Hoisting: Yes, but in temporal dead zone → cannot access before declaration
- Reassignable: Yes
- Redeclarable: No
function exampleLet() {
if (true) {
let y = 20;
console.log(y); // 20
}
// console.log(y); // Error: y is not defined
}
exampleLet();
3️⃣ const
- Scope: Block-scoped
- Hoisting: Yes, but in temporal dead zone
- Reassignable: No (cannot reassign the variable)
- Redeclarable: No
- Note: For objects/arrays, the reference is constant but properties/elements can change
const z = 30;
// z = 40; // Error: Assignment to constant variable
const arr = [1, 2];
arr.push(3); // ✅ Allowed
console.log(arr); // [1, 2, 3]
Quick Comparison
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Reassignable | Yes | Yes | No |
| Redeclarable | Yes | No | No |
| Use Case | Legacy code | Variables that change | Constants / fixed references |
⚡ In short:
Use
letfor variables that can change,constfor constants, and avoidvarin modern JS due to function scoping and hoisting issues.