Conditional Statements ใช้ควบคุม Flow ของโปรแกรม ทำให้โค้ดทำงานต่างกันตามเงื่อนไข JavaScript มี 3 รูปแบบหลัก
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Conditional Statements</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; color: blueviolet; }
</style>
</head>
<body>
<h1>Conditional Statements ใน JavaScript</h1>
<input type="text" class="numInput" placeholder="Enter number" />
<button class="Btn">CHECK</button><br />
<div class="result"></div>
<h3>คลิกปุ่มด้านบนเพื่อเช็คว่าตัวเลขหาร 2, 3 หรือทั้งคู่ลงตัวไหม</h3>
<script>
const resEle = document.querySelector(".result");
const BtnEle = document.querySelector(".Btn");
const numInputEle = document.querySelector(".numInput");
BtnEle.addEventListener("click", () => {
const num = Number(numInputEle.value);
if (Number.isNaN(num)) {
resEle.innerHTML = "กรุณากรอกตัวเลข";
return;
}
if (num % 2 === 0 && num % 3 === 0) {
resEle.innerHTML = "ตัวเลขหาร 2 และ 3 ลงตัวทั้งคู่";
} else if (num % 3 === 0) {
resEle.innerHTML = "ตัวเลขหาร 3 ลงตัว";
} else if (num % 2 === 0) {
resEle.innerHTML = "ตัวเลขหาร 2 ลงตัว";
} else {
resEle.innerHTML = "ตัวเลขไม่หาร 2 หรือ 3 ลงตัว";
}
});
</script>
</body>
</html>
รูปแบบ Conditional Statements
// 1. If Statement (เงื่อนไขเดียว)
if (condition) {
// code
}
// 2. If-Else (2 ทางเลือก)
if (condition) {
// true
} else {
// false
}
// 3. If-Else If-Else (หลายเงื่อนไข)
if (condition1) {
// ...
} else if (condition2) {
// ...
} else if (condition3) {
// ...
} else {
// ไม่มีเงื่อนไขไหนตรง
}
// 4. Ternary Operator (Expression - คืนค่า)
const result = condition ? valueIfTrue : valueIfFalse;
// 5. Short-circuit (Logical Operators)
condition && doSomething(); // ถ้า True ทำ
condition || doSomething(); // ถ้า False ทำ
condition ?? doSomething(); // ถ้า Null/Undefined ทำ (ES2020)
Truthy / Falsy Values
// Falsy (8 ค่า)
false, 0, -0, 0n, "", null, undefined, NaN
// Truthy (อื่นๆ ทั้งหมด)
true, 1, -1, "0", "false", [], {}, function(){}, new Date()
Best Practices
- ใช้
===(Strict Equality) แทน== - จัดรูปแบบ Code ให้อ่านง่าย (Indentation, Braces)
- Early Return / Guard Clauses ลด Nesting
- Switch Statement สำหรับ Multiple Equality Checks
ผลลัพธ์
กรอก 6 → "หาร 2 และ 3 ลงตัวทั้งคู่", กรอก 9 → "หาร 3 ลงตัว", กรอก 4 → "หาร 2 ลงตัว", กรอก 5 → "ไม่หาร 2 หรือ 3 ลงตัว"