Monday 6 November 2017

javascript - What does a tilde do when it precedes an expression?

itemprop="text">

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




~ is a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators?redirectlocale=en-US&redirectslug=Core_JavaScript_1.5_Reference/Operators/Bitwise_Operators"
rel="noreferrer">bitwise operator that flips all bits in its
operand.



For example, if your number was
1, its binary representation of the href="https://en.wikipedia.org/wiki/IEEE_754-1985" rel="noreferrer">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 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes"
rel="noreferrer">Array.prototype.includes() and
href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes"
rel="noreferrer">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.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...