For more tips like this, sign up to the weekly newsletter!

Use String ids from backends

Javascript stores numbers as double precision floating points, which can store both whole and fractional numbers. This gives the comfort of not having to choose between the different representations.

But that can also backfire.

For example, Java has different types for 64 bits whole numbers (called long) and floating points (called double) of similar length.

For large whole numbers, a long can store a greater one than a double.

Number ids

For example, in the case of identifiers, the backend might generate them as longs, and send them as numbers:

[
  {
    "userid": 4393576623199586202,
    "name": "user1"
  },
  ...
]

If you try to parse this object in Javascript, the result will be:

[
  {
    "userid": 4393576623199586300,
    "name": "user1"
  }
  ...
]

Which is not the same, and as identifiers need to be precise, this can easily cause bugs. Also, it's one of the worse kind of bugs, as not all numbers trigger this behavior; only the ones big enough.

Why does this happen?

Large numbers like this cannot be exactly represented using floating points, so Javascript rounds them during the parsing.

To know the largest number that is safe to parse, use Number.MAX_SAFE_INTEGER, which is 9007199254740991.

Use string ids

But there is no such problem with a string identifier:

[
  {
    "userid": "4393576623199586202",
    "name": "user1"
  },
  ...
]

The will be parsed as:

[
  {
    "userid": "4393576623199586202",
    "name": "user1"
  }
  ...
]
Try it
References
Learn more: