We can reach the number from where we have started after using the double tilde (~~) operator, then what is the use of this overhead? The concept is while inverting the number this (~) operator converts them to a 32-bit signed integer which doesn’t keep fractional values. And when we invert that signed integer again, it results in a normal inversion, and due to this, the number either becomes the floor (an integer less than or equal to the number) of the original number or ceil (an integer greater than or equal to the number) of the original number.
Below are the usages of this operator.
- It is used as an alternative for calculating floor instead of using Math.floor(), but the condition given number should be positive.
- It is used as an alternative for calculating the integer part of a fractional number instead of using Math.trunc(), but the condition is that the given number should be negative.
- It is used as an alternative for calculating the ceil instead of using Math.ceil(), but the condition that is given the number should be negative.
- It can be used to convert false values like undefined to zero so it becomes useful when we want to create a counter on such values without facing any errors.
Example 1: The following example demonstrates both of the above functions. First of all, we have declared a variable, and the prompt is taking input from the user. We are using the ~~ operator which will calculate the floor of the number, If the entered number was positive, or it calculates ceil of the number if the entered number was negative.
Example 2: In this example, we will create a counter to check the number of duplicates of a particular type in an array using tilde
Explanation: We do not get any error of undefined while using the counter as the double tilde operator converts the previously undefined value i.e. the value of the undefined array element to zero and it can be used to increment the counter.
Please Login to comment...