node.js - Interpretation of javascript code - Tilde symbol in front of ternary IF operator - Stack Overflow

I was checking the code of respons.js in express and came across this code:res.contentType =res.type =

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?

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?

Share Improve this question asked May 30, 2013 at 20:22 callmekatootiecallmekatootie 11.2k15 gold badges73 silver badges109 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745393473a4625771.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信