Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 20, 2021 11:39 am GMT

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);      // 9007199254740991console.log(Math.pow(2, 53) - 1);        // 9007199254740991

Having the value Math.MAX_SAFE_INTEGER doesnt mean that its 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); // 9007199254740992console.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 youre 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


Original Link: https://dev.to/coderslang/javascript-interview-question-41-going-above-maxsafeinteger-3agl

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To