6
var a = 0;
var b = -a;

When I post the following code to console I got true:

console.log(a === b); // true

But when I do some calculation with it I got false:

console.log(1/a === 1/b); // false

Why is it so?

Dmitriy
  • 3,745
  • 16
  • 24
  • 7
    Because `Infinity` and `-Infinity` aren't equal? – jonrsharpe Mar 20 '16 at 14:11
  • @jonrsharpe, mathematically speaking 1/0 != Infinity. It is undefined. – Sumner Evans Mar 20 '16 at 14:14
  • 5
    I'm not seeing a really strong reason for downvoting this question. Yes, if you try `1 / 0` and `1 / -0` in the console, you'll see `Infinity` and `-Infinity`, and if you look in the specification, you'll find that although `0` and `-0` are considered equal, `Infinity` and `-Infinity` are not. But it's a complex area, it doesn't seem unreasonable to ask about it. – T.J. Crowder Mar 20 '16 at 14:16
  • 2
    @SumnerEvans this isn't maths, it's JavaScript! – jonrsharpe Mar 20 '16 at 14:43
  • Basically, because IEEE 754-2008 says so. – Bergi Mar 20 '16 at 15:04
  • 1
    You can use `Object.is` to distinguish `-0` from `0`. – Bergi Mar 20 '16 at 15:05
  • Yes, @Bergi, in some sort of complex calculation I think that `Object.is` is much better to use then `===`. – Dmitriy Mar 20 '16 at 15:09
  • @DmitriyLoskutov: Nah. You really will expect them to compare equal in your calculations. Notice that `x*0 == 0` is true for all (non-NaN, non-infinite) numbers, but `Object.is(x*0, 0)` is not. There's a good reason why `===` is the default :-) – Bergi Mar 20 '16 at 15:37

1 Answers1

7

That is because Infinity == -Infinity is false, as per abstract equality comparison algorithm.

1/0 will yield Infinity at the same time 1/-0 Yields -Infinity. So both are not are not equal and thus returning false.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130