Types of Variable
| Variable Type | Scope | Reassignment | Redeclaration |
|---|---|---|---|
var | Function | â Yes | â Yes |
let | Block | â Yes | â No |
const | Block | â No | â No |
1. var (Introduced in ES3 - 1999)â
â Strengths:
- Can be redeclared and reassigned.
- Function-scoped (accessible within the function where it's declared).
- Hoisted (moved to the top of the scope).
â Limitations:
- Not block-scoped, meaning it can be accessed outside
{}blocks. - Can cause unintended bugs due to accidental redeclaration.
Exampleâ
var x = 10;
if (true) {
var x = 20; // Redeclaring allowed
}
console.log(x); // 20 (Not block-scoped)
2. let (Introduced in ES6 - 2015)â
â Strengths:
- Block-scoped (only accessible inside
{}where declared). - Can be reassigned but not redeclared in the same scope.
- Prevents hoisting-related issues.
â Limitations:
- Cannot be redeclared within the same block.
Exampleâ
let y = 10;
if (true) {
let y = 20; // This `y` is different (block-scoped)
console.log(y); // 20
}
console.log(y); // 10 (Original `y` remains unchanged)
3. const (Introduced in ES6 - 2015)â
â Strengths:
- Block-scoped like
let. - Cannot be reassigned after declaration.
- Ensures immutability (useful for constants, objects, arrays).
â Limitations:
- Must be assigned a value when declared.
- The reference cannot be changed, but objects/arrays can be modified.
Exampleâ
const z = 30;
// z = 40; // â Error: Cannot reassign a `const` variable
const arr = [1, 2, 3];
arr.push(4); // â
Allowed, modifying array contents
console.log(arr); // [1, 2, 3, 4]