This content originally appeared on DEV Community and was authored by Coderslang: Become a Software Engineer
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
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
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
This content originally appeared on DEV Community and was authored by Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer | Sciencx (2021-05-20T11:39:44+00:00) JavaScript Interview Question #41: Going above MAX_SAFE_INTEGER. Retrieved from https://www.scien.cx/2021/05/20/javascript-interview-question-41-going-above-max_safe_integer/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.