Gothdo Gothdo - 6 months ago 16
Javascript Question

Using Number.isFinite() vs comparing to Infinity vs comparing to Number.POSITIVE_INFINITY to check if a number is finite

There are multiple ways to check if a number is finite.


  1. Using
    Number.isFinite()
    function:

    Number.isFinite(number)

  2. Comparing to
    Infinity
    :

    Math.abs(number) !== Infinity


    I'm using
    Math.abs()
    here in case the number is
    -Infinity
    .

  3. Comparing to
    Number.POSITIVE_INFINITY
    :

    Math.abs(number) !== Number.POSITIVE_INFINITY



Are there any differences between using these three methods? I'm assuming that
Infinity
is read only, as stated in ECMAScript 5 specification.

Answer

2 and 3 are the same because Number.POSITIVE_INFINITY === Infinity. 1 and 2 will handle NaN differently, see http://www.ecma-international.org/ecma-262/6.0/#sec-number.isfinite