0
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.

  • 1
    Maybe see [*Are +0 and -0 the same?*](https://stackoverflow.com/questions/7223359/are-0-and-0-the-same). – RobG Dec 18 '19 at 20:20

2 Answers2

1

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
Ry-
  • 218,210
  • 55
  • 464
  • 476
0

The return value is the two comparisons '&&'ed together. Since it short circuits, if any number outside of 0 or -0 is passed, it will run the first comparison and then return false without ever needing to look at the second.

Eyowzitgoin
  • 129
  • 2
  • 12