I've been reading through some code and noticed a function:
randint: function(n) {
return ~~(Math.random() * n)
}
I know ~ means "not" but how does ~~ change this return statement?
The Complete Full-Stack JavaScript Course! The “double tilde” (~~) operator is a double NOT Bitwise operator. Use it as a substitute for Math.
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's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
The logical NOT ( ! ) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true ; otherwise, returns true .
"but how does ~~ change this return statement?"
Answer: It cuts all fractional digits.
~~42.453754
-> 42
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