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?
To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.
To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
~ 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;
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