Search code examples
javascriptnumbers

Inconsistent addition with `Number.MAX_VALUE`


In Javascript, Number.MAX_VALUE is the biggest value for a number. I got a question that

(Number.MAX_VALUE + 123) == Number.MAX_VALUE  //true
(Number.MAX_VALUE + Number.MAX_VALUE) == Number.MAX_VALUE  //false

I can't understand. Can someone explain me?


Solution

  • In the first example, you just increase your number by a really tiny number: 123 according to 1.79^308 is nothing. So you "lost" some precision: it does not change the number.

    In the second one, you exceed the max value, so your number is not a number anymore, it is Infinity.

    console.log(Number.MAX_VALUE + 123);
    console.log(Number.MAX_VALUE + Number.MAX_VALUE);
    
    /* Is (Number.MAX_VALUE + Number.MAX_VALUE) a number? */
    console.log(Number.isInteger(Number.MAX_VALUE + Number.MAX_VALUE));