Friday, February 28, 2014

Bitwise (Not)

I ran across an odd expression today in the Express config in the MEAN boilerplate.

if (~err.message.indexOf('not found')) return next();

Aside from the omission of the braces, which I'm vehemently against, I thought it looked interesting. Is this is the way the cool kids test for a substring? I played around a little bit, mulled it over, and came to a conclusion.

Test Code

Analysis

Basically, ~ flips the sign and adds -1. It's a neat trick and it saves a couple characters when testing for "anything other than -1". I recall from "JavaScript: The Good Parts" a mention of the inefficiency of JS conversions for bitwise operations. Ignoring that, there are two big problems:

  1. It's tricky. I knew it was a bitwise operator, but couldn't remember which. After dicking around, I see how it works, but will I remember next month? Probably not. If I start using it, what are the chances the other people on my team will know what it is?
  2. It's inconsistent. It doesn't return true or false, it returns something truthy or falsy. You can see that at the end of the gist above.

Conclusion

Don't use it. Code is for humans to read, so clarity is important. Otherwise, we could just write binary, right? Using something that can be easily misunderstood or misused to exhibit how smart you are is a bad practice. We all know you're smart, good-looking, and an excellent driver. Be confident in yourself and considerate to the poor dudes who have to read your code later.


Footnote

The title "Bitwise (Not)" was supposed to be clever; it is the bitwise not operator, but you could also read it as Wayne from Wayne's World. That was supposed to be ironic, because it's not wise to use bitwise operators in JS. Also, it was ironically funny to reference Wayne's World, which was only cool about 20 years ago.

Furthermore, the code snippet tests for "i" in "teamwork"...

Screw it. I'm going to start using ~ to test for indexOf.

No comments:

Post a Comment