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?
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.
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 ...
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.
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.
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
".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With