Have seen '~ ~' can someone explain what it is used for?
Have done google searchs and nothing is returning for this.
It is some math operator but don't know what it is actually doing to numeric values?
Have seen '~ ~' can someone explain what it is used for?
Have done google searchs and nothing is returning for this.
It is some math operator but don't know what it is actually doing to numeric values?
~ is a bitwise operator. By using it twice, some people say its an optimization instead of using Math.floor
like:
var a = 1.9;
Math.floor(a) === ~~a // true (1 === 1)
However 1) Read this answer to understand how is it achieved, and this performance test to see that in some cases the Math.floor()
is faster. It does make sense that Math.floor()
will outperform later on, because that is its purpose!
However 2) Read this answer to see the different effect on negative numbers and some edge cases.
var a = -1.5;
Math.floor(a) !== ~~a // true (-2 !== -1)
However +)
Math.floor(Infinity) !== ~~Infinity // true (Infinity !== 0)
However ++)
Check the comments as well, I'm sure there will be some more interesting aspects.
Personally I prefer readability in such case where the performance is not even a sure thing. Plus the other effects ... just use Math.floor
it's for the best!
See for more bitwise operators: mozzila ref, and how numbers are represented in JavaScript on w3schools.
It's a pair of bitwise complement operators. It's not a single operator.
It's sometimes used to coerce a numeric value to be a 32-bit integer:
var anInteger = ~ ~ aValue;