if / else
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
English
Making decisions
if (test) { ... }runs its block only when the test istrue.elsegives the path to take when the test isfalse.
日本語
判断を作る
if (test) { ... }はテストがtrueの場合にのみそのブロックを実行します。elseはテストがfalseの時の実行パスを指定します。
let age = 20;
if (age >= 18) {
console.log("adult"); // → adult
} else {
console.log("minor");
}
English
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.
日本語
else if で複数の分岐
else ifを追加して選択肢を増やします。JavaScriptは各テストを上から順に確認します。- 最初の
trueとなるテストが勝ち、残りはスキップされます。
let mark = 72;
if (mark >= 70) {
console.log("A"); // → A
} else if (mark >= 50) {
console.log("B");
} else {
console.log("C");
}
Explore · 探索
Which branch runs?
Tests are checked top-down; the first true one runs and the rest are skipped.
English
Watch out
- Put the test in
( )and the block in{ }. - Inside a test, compare with
===(day === "Sat"), never a single=.
日本語
注意
- テストを
( )に、ブロックを{ }に入れます。 - テスト内では
===(day === "Sat")で比較し、単一の=にはしないようにします。
English
Common mistakes
- The condition goes in
( )and the body in{ }. - Compare with
===.
日本語
よくあるミス
- 条件を
( )に、本体を{ }に入れます。 ===で比較します。
English
Now you try
- Read the value, then choose with
if/else. - Press Check answer to test it.
日本語
あなたも試してみよう
- 値を読み取ってから、
if/elseで選択します。 - Check answer を押して確認する。
let n = 5. If n is greater than 0 log positive, otherwise log not positive. (It should log positive.)
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
let mark = 65. Log A for 70 or more, B for 50–69, and C for less. (It should log B.)
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
let n = 4. Log even if n % 2 === 0, otherwise log odd. (It should log even.)
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。