🧠 let, const, and var**
🔸 var – The Old Way (ES5)
- Introduced in early versions of JavaScript.
- Function-scoped
- Can be redeclared and updated
- Hoisted (moved to the top of the scope)
✅ Example:
var x = 10;
var x = 20; // No error (redeclared)
console.log(x); // 20
⚠️ Problem:
if (true) {
var test = "hello";
}
console.log(test); // hello (leaks outside the block)
🔹 let – Modern Way (ES6)
- Introduced in ES6 (2015)
- Block-scoped
- Can be updated but not redeclared in the same scope
- Not hoisted (in a usable way)
✅ Example:
let a = 5;
a = 10; // OK
// let a = 15; ❌ Error: Identifier 'a' has already been declared
if (true) {
let msg = "inside";
console.log(msg); // inside
}
// console.log(msg); ❌ Error: msg is not defined
🔒 const – For Constants (ES6)
- Also block-scoped
- Cannot be updated or redeclared
- Must be initialized at the time of declaration
✅ Example:
const pi = 3.14;
// pi = 3.14159; ❌ Error: Assignment to constant variable
⚠️ Objects with const:
You can change object properties, but not reassign the object.
const person = { name: "Sudhakar" };
person.name = "SK"; // ✅ OK
// person = {}; ❌ Error
📊 Comparison Table
| Feature | var |
let |
const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Yes (initialized as undefined) |
Yes (but not initialized) | Yes (but not initialized) |
| Re-declaration | ✅ Allowed | ❌ Not allowed | ❌ Not allowed |
| Re-assignment | ✅ Allowed | ✅ Allowed | ❌ Not allowed |
| Initialization | Optional | Optional | ✅ Required |
| Use Case | Legacy code | Variables that change | Fixed values / constants |
✅ Best Practices
- Use
constby default - Use
letwhen the value needs to change - Avoid
var(use only in legacy projects)
Top comments (0)