if / else
Making decisions
if (test) { ... }runs its block only when the test istrue.elsegives the path to take when the test isfalse.
การตัดสินใจ
if (test) { ... }จะรันบล็อก เฉพาะเมื่อ เงื่อนไขเป็นtrueelseบอกเส้นทางที่จะ取的เมื่อการทดสอบเป็นfalse
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.
ทางเลือกมากมายด้วย 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");
}
Which branch runs? · ветвь (branch) ใดจะถูกรัน?
Tests are checked top-down; the first true one runs and the rest are skipped. · การทดสอบถูกตรวจสอบ 从上到下; ตัวที่ true แรกจะทำงานและตัวที่เหลือจะถูกข้าม
Watch out
- Put the test in
( )and the block in{ }. - Inside a test, compare with
===(day === "Sat"), never a single=.
ระวัง
- วางเงื่อนไขใน
( )และบล็อคโค้ดใน{ } - ภายในข้อสอบ ให้เปรียบเทียบกับ
===(day === "Sat") ห้ามใช้เพียง=เพียงตัวเดียวเท่านั้น
Common mistakes
- The condition goes in
( )and the body in{ }. - Compare with
===.
ข้อผิดพลาดที่พบบ่อย
- เงื่อนไขอยู่ใน
( )และ Body อยู่ใน{ } - เปรียบเทียบด้วย
===
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.) · let n = 5. หาก n มีค่าน้อยกว่า 0 ให้แสดง positive มิฉะนั้นแสดง not positive. (ควรแสดง positive)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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 สำหรับ 70 ขึ้นไป, B สำหรับ 50–69, และ C สำหรับต่ำกว่า. (ควร log B.)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
let n = 4. Log even if n % 2 === 0, otherwise log odd. (It should log even.) · let n = 4. แสดง even หาก n % 2 === 0 เป็นจริง มิฉะนั้นแสดง odd. (ควรแสดง even)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่