Using let and const in JavaScript
In modern JavaScript (ES6+), let and const are preferred over var for declaring variables. They offer block scoping and help avoid bugs related to variable hoisting and redeclaration.
🔁 let – Mutable Variable
Use let when the value of a variable might change later.
let count = 0;
count = count + 1; // ✅ valid
console.log(count); // 1
Scope: Block-scoped (within { ... })
🔒 const – Constant (Read-only)
Use const when the value should not be reassigned.
const pi = 3.14;
pi = 3.1415; // ❌ Error: Assignment to constant variable
Note: Objects and arrays declared with const can still be mutated:
const user = { name: "John" };
user.name = "Jane"; // ✅ Allowed
const arr = [1, 2, 3];
arr.push(4); // ✅ Allowed
📌 Key Differences
| Feature | let | const |
|---|---|---|
| Reassignable | ✅ Yes | ❌ No |
| Scope | Block | Block |
| Hoisted | Yes (not initialized) | Yes (not initialized) |
🎯 When to Use?
- Use
constby default for safety. - Use
letif you know the variable will change.
✅ Tip: Avoid
var unless you're working in older environments or need function scope specifically.