What You'll Learn
You'll learn how the bitwise NOT operator (~) flips every bit in a number's binary representation—and why that produces surprisingly negative results.
How Bitwise NOT Works
The bitwise NOT operator (~) inverts every single bit in a number's binary form: every 0 becomes 1, and every 1 becomes 0.
Here's the twist: JavaScript represents numbers using two's complement, a system where the leftmost bit indicates sign (negative or positive). When you flip all the bits, you don't just get the opposite number—you get something that looks strange at first.
The Formula
For any integer n:
~n === -(n + 1)
So ~5 equals -6, ~10 equals -11, and ~0 equals -1.
Why This Happens
In binary (using 32 bits), the number 5 is 00000000000000000000000000000101.
When you apply ~5, every bit flips: 11111111111111111111111111111010.
In two's complement notation, that pattern represents -6.
Examples
~5; // -6
~10; // -11
~0; // -1
~-1; // 0
~-5; // 4
Think of It This Way
Imagine a thermometer where flipping the mercury doesn't just reverse direction—it shifts the scale by one notch. The bitwise NOT does something similar due to how negative numbers are stored.
Where It's Used
Bitwise NOT is rarely used in everyday code. You might occasionally see ~ in older patterns like checking if something exists in an array (since indexOf returns -1 when not found), but modern code prefers clearer methods.
Key Takeaway:
The ~ operator inverts all bits, producing -(n + 1) due to JavaScript's two's complement system—making positive numbers negative (and vice versa) in an unexpected way.