Module lessons (4/4)
Conditionals: if, else, ternary
Conditional constructs guide the execution flow by choosing which branch to execute based on a Boolean expression (or its value truthy / false). Clean code prefers flat, readable conditions with early returns over nested pyramids of if.
Mental model: truthy, false and choice of construct
| Constructed | When to choose it | Idiomatic example | Attention |
|---|---|---|---|
Guard clause + return | Edge cases or errors at the beginning of a function | if (!user) return 'Guest'; | Immediately reduces the indentation depth |
if / else if / else | Numeric ranges or compound conditions | if (score >= 90) ... | Only the first true branch is executed |
switch (val) | Many exact discrete values (===) | case 'paid': return ... | Remember break if you don't use return |
Ternary a ? b : c | Assign one of two simple values | age >= 18 ? 'adult' : 'minor' | Don't over nest it in production |
Progressive examples
1. Chain if / else if / else by intervals
function classifyScore(points) {
if (points >= 90) return 'excellent';
if (points >= 70) return 'good';
if (points >= 50) return 'pass';
return 'retry';
}2. The only 6 falsy values and the apparent falsy values
// Falsy: false, 0, '', null, undefined, NaN
Boolean('0'); // true! (stringa non vuota)
Boolean([]); // true! (qualsiasi oggetto/array è truthy)
Boolean('false'); // true!3. Early return against unnecessary nesting
function getDiscountRate(user) {
if (!user || !user.active) return 0;
if (user.tier === 'vip') return 0.25;
return 0.1;
}4. Scope of the variables declared inside the branches
const active = true;
if (active) {
const badge = 'ONLINE'; // accessibile solo qui dentro
console.log(badge);
}Guided laboratory
Ternary expression for outcome
Given grade = 7, write a ternary expression that evaluates to 'promosso' if grade >= 6, otherwise 'bocciato'.
Show hint
Use the syntax condizione ? 'promosso' : 'bocciato'.
Solution available after 3 attempts
Three-band temperature classification
With t = 20, classify the temperature: 'caldo' if >= 25, 'tiepido' if >= 15, 'freddo' otherwise (with t = 20 'tiepido' is expected).
Show hint
You can concatenate two ternaries or assign with if / else.
Solution available after 3 attempts
Guard clause on order status
Implement shippingFee(order): return 0 if !order || order.total >= 50; return 9.9 if order.express === true; otherwise it returns 4.9.
Show hint
Check !order || order.total >= 50 first, then order.express === true.
Solution available after 3 attempts
Check for understanding
Which line will be printed by executing if ([]) console.log('A'); if ('0') console.log('B'); if (0) console.log('C');?
When does it make sense to replace a if / else block with a cond ? a : b ternary operator?