Module lessons (1/4)
Variables: let and const
A variable is a label applied to a value in memory. In modern JavaScript you declare variables with const or let: use const by default and only switch to let when the reference needs to change over time (like a counter or accumulator).
Mental model: label vs container
| Keywords | Brooms | Initial hoisting | Reassignable | Modern use case |
|---|---|---|---|---|
const | Block { ... } | TDZ (ReferenceError) | No (fixed binding) | 90%+ of the variables |
let | Block { ... } | TDZ (ReferenceError) | Yes (x = y) | Counters, temporary states |
var | Function (hole { ... }) | undefined silent | Yes + re-declarable | Pre-ES6 legacy code only |
Progressive examples
1. Fixed binding with const vs rebinding with let
const taxRate = 0.22;
let orderTotal = 100;
orderTotal = orderTotal * (1 + taxRate); // 1222. Because const doesn't make objects immutable
const blocks the link between name and reference, not the internal properties of the object in the Heap:
const user = { name: 'Ada', role: 'editor' };
user.role = 'admin'; // OK: muta l'oggetto nello Heap
// user = { name: 'Leo' }; // TypeError: Assignment to constant variable3. Block scope and block isolation if / for
const discountApplied = true;
let finalPrice = 80;
if (discountApplied) {
const seasonalBonus = 10; // vive solo dentro questo blocco
finalPrice = finalPrice - seasonalBonus; // 70
}
// seasonalBonus qui non esiste: ReferenceError4. Temporal Dead Zone (TDZ) live
Reading let or const before the declaration line immediately generates ReferenceError instead of the misleading undefined produced by var.
Guided laboratory
Constant greeting
Declare a constant greeting with value 'Ciao' (exactly like this). The last expression or the constant itself must produce 'Ciao'.
Show hint
Use const greeting = 'Ciao';.
Solution available after 3 attempts
Changeable accumulator with let
Declare a variable total with let starting from 0, then add 10 and then 5 again. In the end total must be equal to 15.
Show hint
Start from let total = 0; and update with total += 10; total += 5;.
Solution available after 3 attempts
Collision-free block scope
Create an external constant status = 'outside' and a function checkScope(flag) that inside a if (flag) block declares a const status = 'inside' by returning it, while outside the if returns the external status.
Show hint
Inside if (flag) you can declare a new isolated const status = 'inside' to the block.
Solution available after 3 attempts
Check for understanding
What happens when you run const config = { retries: 2 }; config.retries = 5;?
What is the outcome of the following code?
console.log(score);
let score = 100;