Interpreting javascript code - Tilde character before triple IF statement

I checked the respons.js code in the expression 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 type.indexOf() before the type.indexOf() operator? What is its purpose and when is it used?

+8
javascript express
source share
2 answers

This is a bitwise NOT , although its use here is rather opaque.

It is used to convert the result of -1 from indexOf (i.e., the string not found) to 0 , which is a false value (since ~-1 == 0 and 0 is false in the boolean context), and it allows all other values ​​to remain believable.

Could this be written more clearly as (type.indexOf('/') != -1) ? ... : ... (type.indexOf('/') != -1) ? ... : ...

In plain English, it says: "Handle the result -1 (i.e. if / not found) from indexOf as false , otherwise treat the result as true ."

+9
source share

Tilde is a bitwise NOT operator, just like ! is a logical operator NOT. You can take a look at the Mozilla Developer Network operator documentation for its full use and meaning.

0
source share

All Articles