π§© 1. var
- Old way to declare variables (ES5 and earlier).
- Function-scoped: Available throughout the function where itβs declared.
- Hoisting:
var
declarations are hoisted to the top of their scope and initialized as undefined
.
- Can be redeclared and reassigned.
πΉ Example
function exampleVar() {
console.log(a); // undefined (hoisted)
var a = 10;
console.log(a); // 10
}
exampleVar();
- Inside a block (
if
, for
), var
ignores block scope:
if (true) {
var x = 5;
}
console.log(x); // 5 β accessible outside the block
π’ 2. let
- Introduced in ES6.
- Block-scoped: Exists only within
{}
where itβs declared.
- Hoisting: Exists in βtemporal dead zoneβ until initialized β accessing before declaration throws error.
- Can be reassigned but cannot be redeclared in the same scope.
πΉ Example
let b = 10;
b = 20; // β
Reassignment allowed
// let b = 30; // β Error: b already declared
if (true) {
let y = 15;
console.log(y); // 15
}
console.log(y); // β Error: y is not defined outside block
π΅ 3. const
- Also block-scoped.
- Cannot be reassigned (constant reference).
- Must be initialized at declaration.
- For objects/arrays, the reference is constant, but contents can be modified.
πΉ Example
const c = 30;
// c = 40; // β Error: Assignment to constant variable
const arr = [1, 2, 3];
arr.push(4); // β
Allowed, content changes
console.log(arr); // [1, 2, 3, 4]
const obj = { name: "Alice" };
obj.name = "Bob"; // β
Allowed, property changes
π£ 4. Comparison Table
Feature | var | let | const |
---|
Scope | Function-scoped | Block-scoped | Block-scoped |
Hoisting | β
(initialized as undefined) | β
(temporal dead zone) | β
(temporal dead zone) |
Redeclaration | β
Allowed | β Not allowed | β Not allowed |
Reassignment | β
Allowed | β
Allowed | β Not allowed (reference immutable) |
Use Case | Legacy code | Variables that change | Constants or immutable references |
β‘ 5. Hoisting Example
console.log(aVar); // undefined
// console.log(aLet); // β ReferenceError
// console.log(aConst); // β ReferenceError
var aVar = 1;
let aLet = 2;
const aConst = 3;
var
is hoisted with undefined
.
let
and const
are hoisted but in temporal dead zone β cannot be accessed before declaration.
π€ 6. Best Practices
- Avoid
var
in modern JS/TS.
- Use
const
by default, unless you need to reassign.
- Use
let
for variables that will change over time.
- Always respect block scope to prevent bugs.
πΉ Quick Rule of Thumb
const a = 10; // I will not reassign
let b = 20; // I might reassign
// var c = 30; // Only if legacy code requires