Migration of an old post (originally dated: July 4th, 2014).

A couple of days ago I came across a post that talked about “writing code for humans”. To be honest, I skimmed the post, but I do remember seeing an interesting example:

{% highlight javascript linenos %} // Assume this is an array of strings from somewhere var myArray = [“hello”, “something”, “awesome”];

if (~myArray.indexOf(“hello”)) { // Under what circumstances does this get called? } {% endhighlight %}

The author talks about how the code above is equivalent to if (indexOf(“hello”) !== -1) , but does not explain why it is equivalent. This post explains why they are equivalent.

The indexOf function returns either the index of the element to be found, or -1 if it is not found.

With the ~myArray.indexOf example, consider the situation where “hello” is not found. In this scenario, -1 is returned. The binary representation for -1 is done using two’s complement.

Recall that 1 is represented by the bit string “0001”. To make it negative using two’s complement, the formula is to “not” the bit string, then add 1.

For example, “0001” is 1 in binary. We get the representation for -1 by “notting 0001” => (1110), then add 1 (1111).

The binary representation for -1 is “1111”

“~” is the bitwise operator for “not”. If we take “1111” and “not” it, we get the bit string “0000” which represents the integer 0.

Note that zero is considered falsy in JavaScript. Thus ~myArray.indexOf("hello") is evaluated as false if -1; which has the equivalent effect of if (myArray.indexOf("hello") !== -1).