Whats the difference between JS Number.MAX_SAFE_INTEGER and MAX_VALUE?

Number.MAX_SAFE_INTEGER 9007199254740991

Number.MAX_VALUE 1.7976931348623157e+308

I understand how MAX_SAFE_INTEGER is computed based on JavaScript's double precision floating point arithmetic, but where does this huge max value come from? Is it the number that comes about if you're using all 63 bits for the exponent instead of the safe 11 bits?


Solution 1:

Number.MAX_SAFE_INTEGER is the largest integer which can be used safely in calculations.

For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 is true — any integer larger than MAX_SAFE_INTEGER cannot always be represented in memory accurately. All bits are used to represent the digits of the number.

Number.MAX_VALUE on the other hand is the largest number possible to represent using a double precision floating point representation. Generally speaking, the larger the number the less accurate it will be.

More information double-precision floating point numbers on Wikipedia

Solution 2:

JS numbers are internally 64-bits floats (IEEE 754-2008).

MAX_SAFE_INTEGER is the maximum integer that can be safely represented in that format, meaning that all the numbers below that value (and above MIN_SAFE_INTEGER) can be represented as integers.

MAX_VALUE comes from 2^1023 (11 bits mantissa minus mantissa sign), thats about 10^308.

Is it the number that comes about if you're using all 63 bits for the exponent instead of the safe 11 bits?

The mantissa (exponent) is always 11 bits, (not so) surprinsingly that's enough for up to 10^308.