What does a tilde do when it precedes an expression?

wwaawaw picture wwaawaw · Sep 6, 2012 · Viewed 58.2k times · Source
var attr = ~'input,textarea'.indexOf( target.tagName.toLowerCase() )
           ? 'value'
           : 'innerHTML'

I saw it in an answer, and I've never seen it before.

What does it mean?

Answer

alex picture alex · Sep 6, 2012

~ is a bitwise operator that flips all bits in its operand.

For example, if your number was 1, its binary representation of the IEEE 754 float (how JavaScript treats numbers) would be...

0011 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000

So ~ converts its operand to a 32 bit integer (bitwise operators in JavaScript do that)...

0000 0000 0000 0000 0000 0000 0000 0001

If it were a negative number, it'd be stored in 2's complement: invert all bits and add 1.

...and then flips all its bits...

1111 1111 1111 1111 1111 1111 1111 1110

So what is the use of it, then? When might one ever use it?

It has a quite a few uses. If you're writing low level stuff, it's handy. If you profiled your application and found a bottleneck, it could be made more performant by using bitwise tricks (as one possible tool in a much bigger bag).

It's also a (generally) unclear trick to turn indexOf()'s found return value into truthy (while making not found as falsy) and people often use it for its side effect of truncating numbers to 32 bits (and dropping its decimal place by doubling it, effectively the same as Math.floor() for positive numbers).

I say unclear because it's not immediately obvious what it is being used for. Generally, you want your code to communicate clearly to other people reading it. While using ~ may look cool, it's generally too clever for its own good. :)

It's also less relevant now that JavaScript has Array.prototype.includes() and String.prototype.includes(). These return a boolean value. If your target platform(s) support it, you should prefer this for testing for the existence of a value in a string or array.