Module lessons (4/4)
Conditionals: if, else, ternary
A program almost never runs all its instructions in a straight line. It constantly has to decide: if the price is below threshold, apply the discount; if the user is logged in, show the panel; otherwise show the login. The instructions used to make decisions are called conditionals.
if / else
The basic form is if (condition) { … } else { … }:
const eta = 20;
if (eta >= 18) {
console.log('Maggiorenne');
} else {
console.log('Minorenne');
}The condition between parentheses is evaluated; if it is "truthy" (in JS terminology) the first block is executed, otherwise the second one.
else if chains
When there are more than two cases, they are chained with else if:
const punti = 87;
if (punti >= 90) {
console.log('Eccellente');
} else if (punti >= 70) {
console.log('Buono');
} else if (punti >= 50) {
console.log('Sufficiente');
} else {
console.log('Da migliorare');
}Only the first branch that matches is executed.
Truthy and falsy
JS considers six values "falsy": false, 0, '' (empty string), null,
undefined, NaN. Everything else is truthy — even '0', 'false'
and the empty array [].
if ('0') console.log('arriva qui'); // 'arriva qui'
if ([]) console.log('e anche qui'); // 'e anche qui'
if (0) console.log('mai'); // (mai)The ternary operator cond ? a : b
When an if/else only produces a value, the ternary expresses it in
a single line and is often more readable:
const eta = 20;
const stato = eta >= 18 ? 'adulto' : 'minorenne';Try it
Given a grade from 0 to 10, return 'promosso' if the grade is >= 6, otherwise 'bocciato'. The last expression must evaluate to 'promosso' with grade = 7.
Show hint
Use the ternary `cond ? a : b` as the last expression.
Solution available after 3 attempts
Review exercise
Classify a temperature: 'caldo' if >= 25, 'tiepido' if >= 15, 'freddo' otherwise. With `t = 20` the expected result is 'tiepido'.
Show hint
You can nest ternaries: `a >= 25 ? 'caldo' : a >= 15 ? 'tiepido' : 'freddo'`.
Solution available after 3 attempts