Conditions
#HelloFrontend #HelloErmine #HelloWorld2021
Condition คืออะไร ?
คือ โครงสร้างที่จะเลือกทำแค่ส่วนที่ตรงตามเงื่อนไขที่ตั้งไว้ อย่างใดอย่างหนึ่งเท่านั้น
if...else
เราใช้ if else ในการกำหนดให้โปรแกรมของเราตัดสินใจทำคำสั่งใดคำสั่งหนึ่งจากสองทางเลือก โดยผ่านการตรวจสองเงื่อนไขก่อนว่าเป็นจริงหรือเท็จ
ถ้าเงื่อนไขเป็น จริง โปรแกรมจะทำงานภายใต้ block คำสั่ง if
ถ้าเงื่อนไขเป็น เท็จ โปรแกรมจะทำงานภายใต้ block คำสั่ง else
let x = 10;
let result;
if (x === 10) {
result = "x is equal to 10";
} else {
result = "x is NOT equal to 10";
}
console.log(result); // x is equal to 10
switch
เป็นโครงสร้างที่จะเลือกทำจาก case
ที่ตรงกับ expression
และจะทำงานไปเรื่อย ๆ จนถึง break
สามารถกำหนด default
สำหรับกรณีที่ไม่มี case
ใดตรงกับ expression
เลย
let expression = 5;
let result = 0;
switch (expression) {
case 0:
result = result + 10;
break;
case 5:
result = result + 20; // Executed
break;
case 10:
result = result + 30;
break;
default:
result = result + 40;
}
console.log(result); // 20
Ternary operator
หลักการทำงานรูปแบบเดียวกับ if...else แต่วิธีการเขียนจะสั้นลง หรือเรียกได้ว่าเป็นการเขียนแบบ shorthand
เขียนแบบใช้ Ternary operator
let x = 10;
console.log(x === 10 ? true : false); // true
เขียนแบบ if...else เต็มรูปแบบ
let x = 10;
if (x === 10) {
console.log(true); // true
} else {
console.log(false);
}
แหล่งอ้างอิง 📑
Last updated
Was this helpful?