DEV Community

Cover image for JavaScript Interview Question #41: Going above MAX_SAFE_INTEGER
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com

JavaScript Interview Question #41: Going above MAX_SAFE_INTEGER

coderslang javascript interview question #41

True or false? What appears in the console?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

JavaScript uses the double-precision floating-point numbers even to represent integers. This means that the biggest number that can be stored safely as a JS number is 2^53^ - 1 or 9007199254740991. This value is stored as a static constant Math.MAX_SAFE_INTEGER.

console.log(Math.MAX_SAFE_INTEGER);      // 9007199254740991
console.log(Math.pow(2, 53) - 1);        // 9007199254740991
Enter fullscreen mode Exit fullscreen mode

Having the value Math.MAX_SAFE_INTEGER doesn’t mean that it’s impossible to have a bigger number in JS. But, when we continue to increase the number, the loss of precision occurs.

console.log(Number.MAX_SAFE_INTEGER + 1); // 9007199254740992
console.log(Number.MAX_SAFE_INTEGER + 2); // 9007199254740992
Enter fullscreen mode Exit fullscreen mode

As you see, by adding 1 and then 2 to Number.MAX_SAFE_INTEGER, we got the same number.

If you’re building an application where such behavior is critical, then you should use BigInt instead of the regular JavaScript Number.


ANSWER: There will be a loss of precision due to rounding and safe integer overflow. Both x and y will equal 9007199254740992. The message true will be printed to the console.

Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript

Top comments (1)

Collapse
 
liuxuelian profile image
Xuelian Liu

Why Number.MAX_SAFE_INTEGER + 2 !== Number.MAX_SAFE_INTEGER + 3?