Search code examples
javascripttypescriptcomparison

Why is the `n===0` used, as `-0===0` and `0===0` are both true?


function isNegZero(n) {
    n = Number( n );
    return (n === 0) && (1 / n === -Infinity);
}

I am reading the book You don't know JS and found this piece of code there. This is the function to check if the passes number is a -0. I failed to understand as to why the first condition in the comparison is mentioned as it is always going to be true (unless I am wrong in understanding it). Please help.


Solution

  • It’s always going to be true for zero. You want isNegZero(n) to not only be false for +0, but also for any number that is not zero.

    > let n = -Number.MIN_VALUE
    > n === 0
    false
    > 1 / n === -Infinity
    true