メインコンテンツにスキップ
eLearner.app
モジュール 1 · レッスン 4 / 4コース内の 4/32~10 min
モジュールのレッスン (4/4)

条件文: if、else、三項

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 { … }:

JS
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:

JS
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 [].

JS
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:

JS
const eta = 20;
const stato = eta >= 18 ? 'adulto' : 'minorenne';

Try it

運動#js.m1.l4.e1
試行回数: 0読み込み中…

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.

エディターを読み込み中…
ヒントを表示

Use the ternary `cond ? a : b` as the last expression.

3 回の試行後に解決策が利用可能になります

Review exercise

運動#js.m1.l4.e2
試行回数: 0読み込み中…

Classify a temperature: 'caldo' if >= 25, 'tiepido' if >= 15, 'freddo' otherwise. With `t = 20` the expected result is 'tiepido'.

エディターを読み込み中…
ヒントを表示

You can nest ternaries: `a >= 25 ? 'caldo' : a >= 15 ? 'tiepido' : 'freddo'`.

3 回の試行後に解決策が利用可能になります