In JavaScript, why does zero divided by zero return NaN, but any other divided by zero return Infinity?

Because that's how floating-point is defined (more generally than just Javascript). See for example:

  • http://en.wikipedia.org/wiki/Floating-point#Infinities
  • http://en.wikipedia.org/wiki/NaN#Creation

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.


I realize this is old, but I think it's important to note that in JS there is also a -0 which is different than 0 or +0 which makes this feature of JS much more logical than at first glance.

1 / 0 -> Infinity
1 / -0 -> -Infinity 

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 and 0 are different objects in JS, it makes sense to apply the positive 0 to evaluate to positive Infinity and the negative 0 to evaluate to negative Infinity

This logic does not apply to 0/0, which is indeterminate. Unlike with 1/0, we can get two results taking limits by this method with 0/0

lim h->0(0/h) = 0
lim h->0(h/0) = Infinity

which of course is inconsistent, so it results in NaN