Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpretation of javascript code - Tilde symbol in front of ternary IF operator

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?

like image 379
callmekatootie Avatar asked May 30 '13 20:05

callmekatootie


People also ask

What does the tilde mean in JavaScript?

In JavaScript, the tilde ~ Bitwise NOT operator is commonly used right before an indexOf() to do a boolean check (truthy/falsy) on a string. On its own, indexOf() returns the index number of a String object passed in.

What does tilde do in programming?

In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...

How does double tilde work in JavaScript?

It hides the intention of the code. It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.

What is a ternary operator in JavaScript?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


1 Answers

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".

like image 155
apsillers Avatar answered Nov 02 '22 23:11

apsillers