let, const and block scope
When to use let and when to use const, what reassigning means, and why a variable made inside curly braces vanishes after them.
let can change, const cannot
Both make a variable. The difference is whether the name can be pointed at a new value later.
let lives = 3;
lives = lives - 1; // fine: let can be reassigned
const maxLives = 3;
maxLives = 5; // TypeError: Assignment to constant variable.Start with const. Switch to let only when the value really has to change, like a score, a counter or a timer. Anyone reading your code then knows which names move and which stay put. (var is the old way; skip it.)
Curly braces make a block
A variable made with let or const lives inside the nearest pair of { } and nowhere else. That is its scope.
if (score > 100) {
const badge = "Gold";
}
console.log(badge); // ReferenceError: badge is not definedSo if you need a value after a loop or an if, create it before the braces open. Inside, change it; after, read it.
Run it: one name, two blocks
Run it, then change one thing and run it again.
let streak = 0;
const days = ["Mon", "Tue", "Wed"];
for (const day of days) {
const message = day + ": practised";
streak = streak + 1;
console.log(message);
}
console.log("Streak:", streak);
console.log(typeof message);
A total that disappears
This should add up the prices in the basket and print Total: 20. It crashes instead. Move one line so it works.
const prices = [4, 6, 10];
for (const price of prices) {
let total = 0;
total = total + price;
}
console.log(`Total: ${total}`);