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

7 2

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?

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay