I was checking the code of respons.js in express and came across this code:
res.contentType =
res.type = function(type){
return this.set('Content-Type', ~type.indexOf('/')
? type
: mime.lookup(type));
};
My question is what does the ~ operator do in front of the type.indexOf() statement? What is its purpose and when is it used?
It is a bitwise NOT, although its use here is quite opaque.
It is being used to transform a -1 result from indexOf (i.e., string not found) into a 0, which is a falsy value (since ~-1 == 0, and 0 is false in a boolean context), and it lets all other values remain truthy.
It could have been written more clearly as (type.indexOf('/') != -1) ? ... : ...
In plain English, it says, "Treat a -1 result (i.e., if / was not found) from indexOf as false; otherwise, treat the result as true".
The tilde is the bitwise NOT operator, just as ! is the logical NOT operator. You may want to take a look at the documentation of the operator on Mozilla Developer Network for its full usage and meaning.