π§ 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)