ตัวดำเนินการแบบมีเงื่อนไขจะประเมินนิพจน์สำหรับค่าจริงหรือเท็จก่อน จากนั้นจึงดำเนินการหนึ่งในสองคำสั่งที่กำหนดโดยขึ้นอยู่กับผลลัพธ์ของการประเมิน
| Sr.No | ตัวดำเนินการและคำอธิบาย |
|---|---|
| 1 | ? :(มีเงื่อนไข ) ถ้า Condition เป็นจริง? จากนั้นค่า X:มิฉะนั้นค่า Y |
ตัวอย่าง
ลองใช้โค้ดต่อไปนี้เพื่อทำความเข้าใจว่า Conditional Operator ทำงานอย่างไรใน JavaScript:
การสาธิตสด
<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);
document.write(linebreak);
document.write ("((a < b) ? 100 : 200) => ");
result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>