What is the difference between var, let, and const?
Answer
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Reassign | ✅ | ✅ | ❌ |
| Redeclare | ✅ | ❌ | ❌ |
Example
var a = 1;
var a = 2; // OK
let b = 1;
// let b = 2; // Error: already declared
const c = 1;
// c = 2; // Error: assignment to constant
Key Points
- Use
constby default - Use
letwhen you need to reassign - Avoid
varin modern JavaScript