DEV Community

Discussion on: Javascript Tip: a neat trick with the minus tilde for Objects

Collapse
 
kiliman profile image
Kiliman

Nice.

The ~ operator is the bitwise NOT. It inverts the bits. So undefined is treated as 0, and when inverted is 1111111111111111 which is basically -1 in two's-complement.

So now you have -(-1) which is 1.

If you ~1, you get 1111111111111110 which is -2. -(-2) = 2, and so on.

developer.mozilla.org/en-US/docs/W...
en.wikipedia.org/wiki/Two%27s_comp...

Collapse
 
mikkel250 profile image
mikkel250 • Edited

Ahaaa! That's part of what I was failing to understand, is how the two were working together. The minus has the effect of flipping it back to positive. Thanks for the concise explanation!