Infinity - Infinity = NaN?
javascript, math
Solution
As we know that, difference between two numbers can be calculated like this
a - b = a + (-b)
JavaScript uses this to find the difference between two values. Quoting from Applying the Additive Operators to Numbers section from ECMA 5.1 Specification,
The - operator performs subtraction when applied to two operands of numeric type, producing the difference of its operands; the left operand is the minuend and the right operand is the subtrahend. Given numeric operands a and b, it is always the case that a–b produces the same result as a +(–b).
So, when you do
Infinity - Infinity
it is evaluated as
Infinity + (-Infinity)
In JavaScript, they both are different Objects. Quoting from The Number Type section of ECMA 5.1 Specification,
There are two other special values, called positive Infinity and negative Infinity. For brevity, these values are also referred to for expository purposes by the symbols `+∞` and `−∞`, respectively. (Note that these two infinite Number values are produced by the program expressions `+Infinity` (or simply `Infinity`) and `-Infinity`.)
Again, quoting from Applying the Additive Operators to Numbers section from ECMA 5.1 Specification
- If either operand is `NaN`, the result is `NaN`.
- The sum of two infinities of opposite sign is `NaN`.
- The sum of two infinities of the same sign is the infinity of that sign.
- ...
That is why the result is `NaN`.
Problem
Any number minus itself should be `0`, correct? ``` 3 - 3 === 0 ``` Then why ``` Infinity - Infinity === NaN ``` Because `typeof Infinity` is `'number'`: