π§ Introduction:
“Hey developers! Today weβre diving deep into one of the most common JavaScript questions: Whatβs the difference between var, let, and const? Understanding these is crucial for writing modern, bug-free JavaScript. Letβs get into it!”
π 1. var β The Old Way
- Introduced in ES5 (before ES6).
- Function-scoped, not block-scoped.
- Can be re-declared and updated.
- Gets hoisted to the top of its scope with
undefined.
function test() {
console.log(a); // undefined (due to hoisting)
var a = 10;
console.log(a); // 10
}- β Downsides:
- Can lead to bugs due to hoisting.
- Scope leakage due to lack of block scoping.
π 2. let β Modern and Safer
- Introduced in ES6 (2015).
- Block-scoped.
- Can be updated, but not re-declared in the same scope.
- Also hoisted, but not initialized.
function test() {
// console.log(b); // ReferenceError
let b = 20;
console.log(b); // 20
}- β
Use
letwhen you expect the value to change.
π 3. const β Immutable Binding
- Also introduced in ES6.
- Block-scoped like
let. - Cannot be re-assigned or re-declared.
const c = 30;
// c = 40; // TypeError- β However, objects declared with
constare not immutable β just the binding is.
const obj = { name: 'Dev' };
obj.name = 'Coder'; // β
Allowed- β
Use
constby default unless the variable needs to change.
π Comparison Table
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function Scope | Block Scope | Block Scope |
| Hoisting | Yes (undefined) | Yes (TDZ*) | Yes (TDZ*) |
| Re-declare | Yes | No | No |
| Re-assign | Yes | Yes | No |
| Temporal Dead Zone (TDZ) | No | Yes | Yes |
TDZ (Temporal Dead Zone): Time between hoisting and declaration where the variable canβt be accessed.
Should I stop using var?
β
Yes, prefer
let and const β they are block-scoped and safer.When should I use let?
Use
let when the variable’s value is expected to change.When should I use const?
Use
const when the variable will not be reassigned. This helps with code predictability.Can const objects be mutated?
Yes, the reference is constant, not the object itself.
What happens if I access let or const before declaration?
You get a ReferenceError due to the Temporal Dead Zone.
