indexOf != 1 vs. !~indexOf


Blogging isn’t really my thing, but if I am to have a website with my name on it. Well I may as well use it.

More like having free time isn’t my thing. Having a young family is super awesome yet it takes a lot of time away from extracurricular activities! Like writing blog entries.

Anyways on to the substance of this super short filler post.

The other day I saw an interesting snippet of JavaScript code, in one of my junior’s projects:

if (!~file.indexOf('js'))

I’m so used to seeing this:

if (file.indexOf('js') != -1)

I had to investigate.

I recognized the ~ as the negation bit wise operator. How was this working I asked myself. Well it is simple, and I love it. The ~ operator negates all the bits in a variable turning 1s into 0s and 0s into 1s.

Looking at the if statement. The only integer value that would pass that if statement is 0.

So I ask you this what integer value when negated results in 0?

If you guessed -1 you are right. Yup -1 in binary results in all 1s. Twos compliment. The first bit is the sign bit and then the rest denote the number. Since negative numbers are reversed in binary all 1s is the lowest negative value -1.  (might actually be different in JS since it is technically a double)

If indexOf fails it returns -1. Plus JavaScript is one of the few languages you can say if not zero. ~indexOf != 0 would be kinda silly no? I’d expect this technique would be odd in C, but could work in maybe PHP?

And ultimately yes… there is little space saved here, and what optimizations are being made? None really doing it this way. It is just cool to see something different now and then.