Conditional operator (Ternary operator) ประเมิน expression ว่า true/false แล้ว execute statement หนึ่งในสองstatement ตามผลลัพธ์
| ลำดับ | Operator และ คำอธิบาย |
|---|---|
| 1 | ? : (Conditional/Ternary) If Condition is true? Then value X: Otherwise value Y |
ตัวอย่าง
<html>
<body>
<script>
var a = 10, b = 20, linebreak = "<br />";
document.write("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);
document.write("((a < b) ? 100 : 200) => ");
result = (a < b) ? 100 : 200;
document.write(result);
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Syntax
condition ? expressionIfTrue : expressionIfFalse
ตัวอย่างการใช้งานจริง
// แทน if-else สำหรับการกำหนดค่า const status = isOnline ? "Online" : "Offline"; const fee = isMember ? 0 : 100; const canVote = age >= 18 ? "Yes" : "No"; // Nested ternary (ใช้ด้วยความระมัดระวัง - อ่านยาก) const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F"; // แนะนำ: ใช้ if-else หรือ switch สำหรับ logic ซับซ้อน
Nullish Coalescing (ES2020) — ??
คล้าย ternary แต่สำหรับ null/undefined เท่านั้น:
const name = userName ?? "Anonymous"; // ถ้า userName เป็น null/undefined ใช้ "Anonymous" // ต่างจาก || ที่จับ falsy ทุกค่า (0, "", false)