Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Is '~ ~' in Javascript? [duplicate]

Tags:

javascript

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?

like image 376
Dere_2929 Avatar asked Jan 16 '14 21:01

Dere_2929


People also ask

How do you check if there is a duplicate in an array JavaScript?

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.

How can you remove duplicates from a JS array?

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.

What is a duplicate element?

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.


2 Answers

~ 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.

like image 159
p1100i Avatar answered Sep 20 '22 03:09

p1100i


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;
like image 38
Pointy Avatar answered Sep 22 '22 03:09

Pointy