let, const & Block Scope
Before ES6, JavaScript had only var. It had confusing rules — variables could “leak” outside if blocks and loops. ES6 added let and const with block scope: variables live only inside the { } where you declare them.
const — value you will not reassign
const API_URL = 'https://api.toolliyo.com';
const MAX_LOGIN_ATTEMPTS = 5;
// API_URL = 'other'; // ❌ Error — cannot reassign const
Use const by default for variables that should not point to a new value.
let — value that can change
let score = 0;
score = score + 10; // ✅ OK
score += 5;
Block scope in action
if (user.isLoggedIn) {
const welcome = 'Hello, ' + user.name;
let visitCount = 1;
}
// console.log(welcome); // ❌ Error — not visible outside block
🌍 Real-world example — Shopping cart item count
function updateCart(items) {
let total = 0;
for (const item of items) {
const lineTotal = item.price * item.qty; // const — per iteration
total += lineTotal;
}
return total;
}
updateCart([
{ name: 'Node.js ebook', price: 499, qty: 1 },
{ name: 'React course', price: 999, qty: 2 }
]); // 2497const with objects and arrays
const prevents reassignment, not mutation:
const user = { name: 'Alex', role: 'student' };
user.role = 'admin'; // ✅ OK — editing property
// user = {}; // ❌ Error — reassigning variable
const tags = ['javascript', 'es6'];
tags.push('react'); // ✅ OK
// tags = []; // ❌ Error
⚠️ Common Mistake: Using var in new code. var is function-scoped and hoisted in confusing ways — avoid it in 2026 projects.
💡 Tip: Rule of thumb: const always, let when you need to reassign, never var.
👨🏫 Teaching note: Demo the loop bug:
for (var i=0; i<3; i++) setTimeout(() => console.log(i), 100) prints 3,3,3. With let it prints 0,1,2.