In JavaScript, variables can be declared using var, let, or const. Though they all serve the same fundamental purpose—declaring variables—they behave quite differently in terms of scope, hoisting, reassignment, and more.
Let’s break down their key differences.
🔁 1. Scope: Global, Function, and Block
| Feature | var |
let |
const |
|---|---|---|---|
| Scope type | Function-scoped | Block-scoped | Block-scoped |
👉 var – Function Scope
Variables declared with var are function-scoped, which means they are only accessible inside the function in which they are defined.
function example() {
if (true) {
var x = 10;
}
console.log(x); // ✅ 10 - accessible because var is function-scoped
}
👉 let and const – Block Scope
Both let and const are block-scoped, meaning they only exist within the enclosing {} block.
function example() {
if (true) {
let y = 20;
const z = 30;
}
console.log(y); // ❌ ReferenceError
console.log(z); // ❌ ReferenceError
}
📦 2. Hoisting Behavior
👉 var is hoisted and initialized.
console.log(a); // ✅ undefined
var a = 5;
👉 let and const are hoisted but not initialized
console.log(b); // ❌ ReferenceError (TDZ)
let b = 10;
🔁 3. Redeclaration & Reassignment
👉 var allows redeclaration and reassignment
var x = 1;
var x = 2; // ✅ No error
x = 3; // ✅ No error
👉 let allows reassignment but not redeclaration
let y = 1;
let y = 2; // ❌ SyntaxError
y = 3; // ✅ Allowed
👉 const allows neither
const z = 1;
const z = 2; // ❌ SyntaxError
z = 3; // ❌ TypeError
⛔ 4. Temporal Dead Zone (TDZ)
The Temporal Dead Zone (TDZ) is the period between entering the scope and the actual declaration where variables declared with let and const cannot be accessed.
function test() {
console.log(a); // ❌ ReferenceError (TDZ)
let a = 10;
}
With var, accessing the variable before the declaration just returns undefined, but with let and const, it throws an error due to the TDZ.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.