JavaScript รองรับ comparison operators ต่อไปนี้ สมมติ A = 10, B = 20:
| ลำดับ | Operator และ คำอธิบาย |
|---|---|
| 1 | == (Equal) เช็คค่าของสอง operand เท่ากันหรือไม่ (type coercion) Ex: (A == B) is not true. |
| 2 | != (Not Equal) เช็คค่าของสอง operand ไม่เท่ากัน (type coercion) Ex: (A != B) is true. |
| 3 | > (Greater than) เช็ค operand ซ้ายมากกว่าขวา Ex: (A > B) is not true. |
| 4 | < (Less than) เช็ค operand ซ้ายน้อยกว่าขวา Ex: (A < B) is true. |
| 5 | >= (Greater than or Equal) เช็ค operand ซ้ายมากกว่าหรือเท่าขวา Ex: (A >= B) is not true. |
| 6 | <= (Less than or Equal) เช็ค operand ซ้ายน้อยกว่าหรือเท่าขวา Ex: (A <= B) is true. |
Strict Equality (แนะนำใช้)
| Operator | ชื่อ | พฤติกรรม |
|---|---|---|
=== | Strict Equal | เช็คค่าและชนิดข้อมูล (ไม่ type coercion) |
!== | Strict Not Equal | เช็คค่าหรือชนิดข้อมูลต่างกัน |
1 == "1" // true (loose equality - type coercion) 1 === "1" // false (strict equality - ต่าง type) null == undefined // true null === undefined // false
แนะนำ: ใช้ === และ !== เสมอ เพื่อหลีกเลี่ยง type coercion ที่สับสน
ตัวอย่างโค้ด
<html>
<body>
<script>
var a = 10, b = 20, linebreak = "<br />";
document.write("(a == b) => "); result = (a == b); document.write(result); document.write(linebreak);
document.write("(a < b) => "); result = (a < b); document.write(result); document.write(linebreak);
document.write("(a > b) => "); result = (a > b); document.write(result); document.write(linebreak);
document.write("(a != b) => "); result = (a != b); document.write(result); document.write(linebreak);
document.write("(a >= b) => "); result = (a >= b); document.write(result); document.write(linebreak);
document.write("(a <= b) => "); result = (a <= b); document.write(result); document.write(linebreak);
</script>
</body>
</html>