DEV Community

Discussion on: A neat little trick with JavaScript's indexOf()

Collapse
 
reegodev profile image
Matteo Rigon • Edited

If someone's interested in why it actually works ( as Patrick should have been 😉) it's because numbers in javascript are represented as 32 bits in two's complement format.

That means that negative numbers have all bits inverted and then get added 1:

1 = 0000 0000 0000 0000 0000 0000 0000 0001
-1 = 1111 1111 1111 1111 1111 1111 1111 1111
10 = 0000 0000 0000 0000 0000 0000 0000 1010
-10 = 1111 1111 1111 1111 1111 1111 1111 0110

So if you apply the bitwise NOT only -1 can become 0 and thus be falsy