if / else
Making decisions
if (test) { ... }runs its block only when the test istrue.elsegives the path to take when the test isfalse.
Prendre des décisions
if (test) { ... }exécute son bloc uniquement lorsque le test esttrue.elsedéfinit le chemin à suivre quand le test estfalse.
let age = 20;
if (age >= 18) {
console.log("adult"); // → adult
} else {
console.log("minor");
}
Many paths with else if
- Add
else iffor more choices. JavaScript checks each test top to bottom. - The first test that is
truewins; the rest are skipped.
De nombreux chemins avec else if
- Ajoutez
else ifpour plus de choix. JavaScript vérifie chaque test de haut en bas. - Le premier test qui est
truegagne ; les autres sont ignorés.
let mark = 72;
if (mark >= 70) {
console.log("A"); // → A
} else if (mark >= 50) {
console.log("B");
} else {
console.log("C");
}
Which branch runs? · Quelle branche s'exécute ?
Tests are checked top-down; the first · premier true one runs and the rest are skipped. · Les tests sont vérifiés de haut en bas ; le premier vrai s'exécute et les autres sont ignorés.
Watch out
- Put the test in
( )and the block in{ }. - Inside a test, compare with
===(day === "Sat"), never a single=.
Attention
- Placez le test dans
( )et le bloc dans{ }. - Dans un test, comparez avec
===(day === "Sat"), jamais un simple=.
Common mistakes
- The condition goes in
( )and the body in{ }. - Compare with
===.
Erreurs courantes
- La condition va dans
( )et le corps dans{ }. - Comparez avec
===.
Now you try
- Read the value, then choose with
if/else. - Press Check answer to test it.
À vous maintenant
- Lisez la valeur, puis choisissez avec
if/else. - Appuyez sur Vérifier la réponse pour tester.
let n = 5. If n is greater than 0 log positive, otherwise log not positive. (It should log positive.) · let n = 5. Si n est supérieur à 0, log positive, sinon log not positive. (Il devrait log positive.)
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
let mark = 65. Log A for 70 or more, B for 50–69, and C for less. (It should log B.) · let mark = 65. Log A pour 70 ou plus, B pour 50-69, et C pour moins. (Il devrait log B.)
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
let n = 4. Log even if · si n % 2 === 0, otherwise log odd. (It should log even.) · let n = 4. Log even si n % 2 === 0, sinon log odd. (Il devrait log even.)
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.