It seems to me that the code
console.log(1 / 0)
should return NaN
, but instead it returns Infinity
. However this code:
console.log(0 / 0)
does return NaN
. Can someone help me to understand the reasoning for this functionality? Not only does it seem to be inconsistent, it also seems to be wrong, in the case of x / 0
where x !== 0
I realize this is old, but I think it's important to note that in JS there is also a
-0
which is different than0
or+0
which makes this feature of JS much more logical than at first glance.which logically makes sense since in calculus, the reason dividing by 0 is undefined is solely because the left limit goes to negative infinity and the right limit to positive infinity. Since the
-0
and0
are different objects in JS, it makes sense to apply the positive 0 to evaluate to positiveInfinity
and the negative 0 to evaluate to negativeInfinity
This logic does not apply to
0/0
, which is indeterminate. Unlike with1/0
, we can get two results taking limits by this method with0/0
which of course is inconsistent, so it results in NaN
Because that's how floating-point is defined (more generally than just Javascript). See for example:
Crudely speaking, you could think of 1/0 as the limit of 1/x as x tends to zero (from the right). And 0/0 has no reasonable interpretation at all, hence NaN.
In addition to answers based on the mathematical concept of zero, there is a special consideration for floating point numbers. Every underflow result, every non-zero number whose absolute magnitude is too small to represent as a non-zero number, is represented as zero.
0/0 may really be 1e-500/1e-600, or 1e-600/1e-500, or many other ratios of very small values.
The actual ratio could be anything, so there is no meaningful numerical answer, and the result should be a NaN.
Now consider 1/0. It does not matter whether the 0 represents 1e-500 or 1e-600. Regardless, the division would overflow and the correct result is the value used to represent overflows, Infinity.