In this lesson: Choose correctly between const and let, and avoid var.
A variable is a name for a value.
let age = 24;
const country = 'Rwanda';
Which keyword?
const— the name cannot be reassigned. Use this by default.let— use only when the value genuinely needs to change (a counter, a loop variable).var— the old way. Its scoping rules cause bugs. Do not use it in new code.
const city = 'Kigali';
city = 'Huye'; // TypeError: Assignment to constant variable
let score = 0;
score = score + 10; // fine
const does not mean frozen. It stops the name being pointed at something else. The contents of an object or array can still change:
const list = [1, 2];
list.push(3); // fine — list is still the same array
list = [9]; // error — reassigning the name
Block scope
let and const exist only inside the { } they were declared in:
if (true) {
const secret = 'hidden';
console.log(secret); // 'hidden'
}
console.log(secret); // ReferenceError — it does not exist here
This is exactly what you want. var ignores block scope and leaks out of the braces, which is why it causes trouble.
Naming things well
// Poor
let x = 34.99;
let d = true;
// Good
let priceInUsd = 34.99;
let isPublished = true;
You will read code far more often than you write it. Names are documentation.