Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Conditional Operator (?:) ใน JavaScript คืออะไร

Conditional Operator (Ternary Operator) เป็นออเปอเรเตอร์ตัวเดียวใน JS ที่รับ 3 Operand ใช้ตัดสินใจเลือกค่าระหว่าง 2 ทางเลือก

ตัวอย่างจากบทความ

<html>
  <body>
    <script>
      var a = 10;
      var b = 20;
      var linebreak = "<br />";
      document.write("((a > b) ? 100 : 200) => ");
      result = (a > b) ? 100 : 200;
      document.write(result); // 200
      document.write(linebreak);
      document.write("((a < b) ? 100 : 200) => ");
      result = (a < b) ? 100 : 200;
      document.write(result); // 100
      document.write(linebreak);
    </script>
  </body>
</html>

ไวยากรณ์

condition ? expressionIfTrue : expressionIfFalse
ส่วนคำอธิบาย
conditionนิพจน์ที่ประเมินเป็น true/false
?ถ้า true ให้ค่าด้านซ้าย
:ถ้า false ให้ค่าด้านขวา

ตัวอย่างการใช้งานจริง

1. Simple Conditional Assignment

const isAdult = age >= 18 ? 'Yes' : 'No';
const status = isOnline ? '🟢 Online' : '🔴 Offline';
const fee = isMember ? 0 : 100;

2. Null/Undefined Check

const displayName = user.name ? user.name : 'Anonymous';
// หรือใช้ Nullish Coalescing (ES2020)
const displayName = user.name ?? 'Anonymous';

3. Inline в JSX/Template

// React JSX
{isLoggedIn ? : }
// Template Literals const message = `Welcome ${user ? user.name : 'Guest'}`;

4. Nested Ternary (ควรหลีกเลี่ยงถ้าซับซ้อน)

const grade = score >= 90 ? 'A' :
              score >= 80 ? 'B' :
              score >= 70 ? 'C' :
              score >= 60 ? 'D' : 'F';

// ดีกว่า: ใช้ if-else หรือ lookup table
const grades = [
  [90, 'A'], [80, 'B'], [70, 'C'], [60, 'D'], [0, 'F']
];
const grade = grades.find(([min]) => score >= min)[1];

5. Function Return

function getDiscount(price, isMember) {
  return isMember ? price * 0.9 : price;
}

// Arrow function
const getDiscount = (price, isMember) => isMember ? price * 0.9 : price;

เทียบกับ if-else Statement

if-else (Statement)Ternary (Expression)
ไม่คืนค่าคืนค่า (Expression)
หลายบรรทัดบรรทัดเดียว
ใช้ได้ทุกที่ใช้ได้ที่ต้องการ Expression
อ่านง่าย (Complex logic)อ่านง่าย (Simple logic)
// if-else
let result;
if (condition) {
  result = 'yes';
} else {
  result = 'no';
}

// ternary
const result = condition ? 'yes' : 'no';

ข้อควรระวัง

  • Precedence: ต่ำกว่าการคำนวณส่วนใหญ่ → ใช้วงเล็บครอบ condition
  • Nested: ยากต่อการอ่าน > 2 ระดับ → ใช้ if-else
  • Side Effects: ไม่ควรทำ side effect ใน ternary (อ่านยาก)
  • Type Consistency: ทั้งสอง branch ควรคืน type เดียวกัน

Nullish Coalescing (??) vs Ternary

// Ternary - ตรวจสอบ falsy ทั้งหมด
const value = input !== null && input !== undefined ? input : 'default';

// ?? - ตรวจสอบ null/undefined เท่านั้น (ES2020)
const value = input ?? 'default';