Ok, this will sound crazy, but I’ve tested it on several browsers and three different machines (all Windows though). As soon as I assign specific numeric value to the variable, it immediately increments. The problem for me is that this specific value is one of the database object ids that shouldn’t be changed.
Tried on latest Chrome, Firefox, and Edge. It’s really simple to test:
let a = 17841410687956931;
console.log(a);
// output is 17841410687956932
I’ve also tried let a = [17841410687956931];
and let a = {17841410687956931: "anything"};
, and it still increments. const
and var
don’t change a thing. Note that 17841410687956930 and 17841410687956932 are perfectly fine and do not misbehave.
Am I seeing things? Can this be some easter egg? Can you recommend me a good doctor?
3
Answers
JavaScript uses precision defined by the IEEE 754 by default. This format provides 53 bits of precision for integer values. The number you provided, 17841410687956931, requires more than 53 bits.
Use BigInt which was introduced in ECMAScript 2020:
This is a precision issue related to JavaScript’s large number processing. JavaScript uses a 64-bit floating-point representation for numbers, and beyond a certain point, it can no longer accurately represent consecutive integers.
Try converting your number to BigInt by adding "n" at the end, like this:
"n" tells JavaScript to treat the number as
BigInt
, which will handle large integers more accurately.Use BigInt in order to work with integers of arbitrary Precision without losing accuracy:
So this is not a bug but we can say one of the limitation of JS handling large integer values, since it use IEEE754 standard for double-precision in this case the precision of storing integers is only 53bits.