โอเปอเรเตอร์ลบ (-) ใช้ ลบ operand ขวามือออกจาก operand ซ้ายมือ (Left - Right) เป็น Binary Operator (รับ 2 operand)
ตัวอย่างโค้ด
<html>
<body>
<script>
var a = 40;
var b = 25;
document.write("a - b = ");
result = a - b;
document.write(result); // 15
</script>
</body>
</html>
พฤติกรรมกับชนิดข้อมูล (Type Coercion)
ไม่เหมือน + ที่ต่อสตริง - จะ พยายามแปลง operand ทั้งสองเป็นตัวเลขเสมอ:
| Operand 1 | Operand 2 | ผลลัพธ์ | คำอธิบาย |
|---|---|---|---|
| 10 | 5 | 5 | ตัวเลขปกติ |
| "10" | 5 | 5 | String → Number |
| 10 | "5" | 5 | String → Number |
| "10" | "5" | 5 | ทั้งคู่ String → Number |
| true | false | 1 | true=1, false=0 |
| null | 5 | -5 | null=0 |
| undefined | 5 | NaN | undefined=NaN |
| "abc" | 5 | NaN | "abc" ไม่แปลงเป็นตัวเลขได้ |
Unary Negation (-) vs Binary Subtraction (-)
สัญลักษณ์ - มี 2 หน้าที่:
| ประเภท | ชื่อ | ตัวอย่าง | ผลลัพธ์ |
|---|---|---|---|
| Unary | Negation | -5, -x | กลายเป็นลบ / บวก |
| Binary | Subtraction | 10 - 3 | ลบ |