Bitwise Not & indexOf

Honestly, I’ve found precious few instances in which I need to use javascript’s bitwise not operator. However, I stumbled across a particularly nice usage of it this morning as I was perusing the express source.

When I use indexOf to check for a substring I often feel the statement is rather clumsy, especially if the variable name is particularly long.

if (someLongVariableName.indexOf(someSubstring) == -1) {
  // do stuff

The == -1 part seems to get lost at the end of the expression and it takes me an extra moment to parse the code. However, I found this brilliant little nugget that makes it much easier to read.

res.contentType = function(type){
  if (!~type.indexOf('.')) type = '.' + type;
  return this.header('Content-Type', mime.type(type));

Taking advantage of the fact that ~(-1) == 0 (and it is the only number with this property), our statement becomes truthy or falsey and we can change our previous example to

if (!~someLongVariableName.indexOf(someSubstring)) {
  // do stuff