if / else
Making decisions
if (test) { ... }runs its block only when the test istrue.elsegives the path to take when the test isfalse.
Membuat keputusan
if (test) { ... }menjalankan bloknya hanya ketika tes bernilaitrue.elsemenentukan jalur yang diambil ketika tes adalahfalse.
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.
Banyak jalur dengan else if
- Tambahkan
else ifuntuk pilihan lebih lanjut. JavaScript memeriksa setiap tes dari atas ke bawah. - Tes pertama yang bernilai
truemenang; sisanya dilewati.
let mark = 72;
if (mark >= 70) {
console.log("A"); // → A
} else if (mark >= 50) {
console.log("B");
} else {
console.log("C");
}
Which branch runs? · Cabang mana yang dijalankan?
Tests are checked top-down; the first true one runs and the rest are skipped. · Uji dicek dari atas ke bawah; yang pertama benar akan dijalankan dan sisanya dilewati.
Watch out
- Put the test in
( )and the block in{ }. - Inside a test, compare with
===(day === "Sat"), never a single=.
Hati-hati
- Letakkan tes di
( )dan blok di{ }. - Di dalam tes, bandingkan dengan
===(day === "Sat"), jangan gunakan=tunggal.
Common mistakes
- The condition goes in
( )and the body in{ }. - Compare with
===.
Kesalahan umum
- Kondisi masuk di
( )dan badan di{ }. - Bandingkan dengan
===.
Now you try
- Read the value, then choose with
if/else. - Press Check answer to test it.
Sekarang Anda coba
- Baca nilainya, lalu pilih dengan
if/else. - Tekan Cek jawaban untuk mengujinya.
let n = 5. If n is greater than 0 log positive, otherwise log not positive. (It should log positive.) · let n = 5. Jika n > 0 log positive, jika tidak log not positive. (Seharusnya log positive.)
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
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 untuk ≥70, B untuk 50–69, dan C untuk kurang. (Seharusnya log B.)
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
let n = 4. Log even if n % 2 === 0, otherwise log odd. (It should log even.) · let n = 4. Log even jika n % 2 === 0, jika tidak log odd. (Seharusnya log even.)
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.