I have often seen this in JavaScript:
var val = (myvar / myothervar) | 0;
Which as far as I understood was one of the many shortcuts to floor a value in JavaScript (like ~~
, and >> 0
, etc). However, I was looking at a piece of code recently that did this:
var val = Math.floor(myvar/ myothervar)|0;
They used Math.floor()
and then also did a bitwise OR with 0
. The author did this many times, so it wasn't just a typo they did once. What do you gain by doing both?
For the curious, the code I am referring to can be found here
The Math.floor() function always rounds down and returns the largest integer less than or equal to a given number.
floor() method rounds a number DOWN to the nearest integer, if necessary, and returns the result.
The FLOOR. MATH function rounds a number down to the nearest integer or a multiple of specified significance, with negative numbers rounding toward or away from zero depending on the mode.
The Math. floor() function in JavaScript is used to round off the number passed as parameter to its nearest integer in Downward direction of rounding i.g towards the lesser value. Hence, math. floor(3.6) = 3.
You might not have thought of:
Math.floor(NaN) == NaN
(ok, not really, but Math.floor(NaN)
is NaN
)Math.floor(NaN) | 0 == 0
Also relevant for Infinity
As pointed out by @apsillers, this is probabably to eliminate Infinity
s:
var x = 1;
console.log(Math.floor(1 / x)); // 1
console.log(Math.floor(1 / x) | 0); // 1
x = 0;
console.log(Math.floor(1 / x)); // Infinity
console.log(Math.floor(1 / x) | 0); // 0
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