- Published at
- Updated at
- Reading time
I was in Cluj-Napoca the last few days to speak at the excellent JSHeroes conference and saw a fascinating code snippet in Mathias Bynens' talk "V8 Internals for JS Developers" (the recording is from a different event).
Object.is(-0, +0); // false
This single line is fascinating in two ways – let's have a look!
const posNumber = 1; const negNumber = -1; const posZero = +0; const negZero = -0;
My first reaction to discovering negative zeros was that I surely don't have these in my code, but you will be surprised! Round
-0, and you'll end up with a negative zero. So it might be possible that you have to treat negative zeros in your code, too.
Math.round(-0.23); // -0
But there's more; compare a positive and negative zero and you'll discover that they're treated equal! 😲
-0 === +0 // true
But there's a nicer way of dealing with
Strict comparison with
NaN, which is not equal to itself.
NaN === NaN // false // Tip: you can use Number.isNaN as an alternative Number.isNaN(NaN) // true
These quirks are when
Object comes into play. In most cases, it behaves the same as
===, but it includes some minor "improvements" making things more logical. Let's look at the zero and
Object.is(-0, 0); // false Object.is(NaN, NaN); // true
Object differentiates positive and negative zeros and it's even able to detect
Object for the first time in Mathias' slides, and it doesn't seem to be used that often. Do you have
Object in your source code?