Operator Bitwise NOT (~) ทำการกลับบิต (Invert Bits) ของตัวเลข 32-bit Signed Integer หมายถึง บิต 0 จะกลายเป็น 1 และบิต 1 จะกลายเป็น 0
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<script>
document.write("Bitwise NOT Operator<br>");
// 7 = 00000000000000000000000000000111 (32-bit)
document.write(~7); // ผลลัพธ์: -8
</script>
</body>
</html>
การคำนวณ
- 7 ใน Binary (32-bit):
00000000000000000000000000000111 - กลับบิตทั้งหมด:
11111111111111111111111111111000 - ค่านี้คือ -8 ในรูปแบบ Two's Complement
สูตรเร็ว
~x === -(x + 1) เช่น ~7 === -8, ~0 === -1, ~-1 === 0
การใช้งานจริง: ใช้บ่อยในการตรวจสอบ indexOf() แบบสั้นๆ เช่น ~str.indexOf('text') จะเป็น true (Truthy) ถ้าพบ และ false (Falsy = 0) ถ้าไม่พบ