skip to Main Content

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


  1. 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:

    let a = BigInt("17841410687956931");
    console.log(a);
    
    Login or Signup to reply.
  2. 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:

    let a = 17841410687956931n;
    console.log(a);

    "n" tells JavaScript to treat the number as BigInt, which will handle large integers more accurately.

    Login or Signup to reply.
  3. Use BigInt in order to work with integers of arbitrary Precision without losing accuracy:

    let a = BigInt("17841410687956931");
    console.log(a.toString());  // output is 17841410687956931

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search