-3

In JavaScript, isNaN(Infinity) returns false, as if Infinity were a number; but several arithmetic operations on Infinity behave as if it were the mathematical infinity, which is not a number:

enter image description here

So, why doesn't isNaN(Infinity) return true? Is it because its value defaults to a Number object?

georg
  • 211,518
  • 52
  • 313
  • 390
wcr4
  • 55
  • 8

2 Answers2

1

Infinity is not NaN because you are able to use it in mathematical expressions. Obviously 1 + NaN would never work, but 1 + Infinity returns Infinity (See here). Many of the examples that you have in your link are mathematically indeterminate, which is why they return as Nan. For example, Infinity * 0 is indeterminate (See here).

Hope this helps.

Community
  • 1
  • 1
Brian Howell
  • 67
  • 2
  • 13
0

The reason isNaN(Infinity) returns false has nothing to do with mathematical technicalities, it's simply because its implementation is equal to this:

function isNaN(object) {
  var coerced = +object;

  return coerced !== coerced;
}

In other words, it coerces the input to a Number. If the coerced value is determined to be NaN (by checking if it is not strictly equal to itself), then it returns true. Otherwise it returns false.

[Infinity, null, undefined, true, new Date(), {}, [], [1], [1,2,3], 'blah', '4'].forEach(function (object) {
  console.log('object: ' + (typeof object !== 'number' ? JSON.stringify(object) : object));
  console.log('coerced: ' + (+object));
  console.log('isNaN: ' + isNaN(object));
  console.log('==================');
});
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153