There is something about mechanical keyboards that makes sense to me, probably the feeling of progress with every click, the sound of it, the interaction, the satisfaction, simply love it.

Beware of “Integer” problem in JavaScript

The case

Recently while working on a project, I got a weird bug with displaying Integer in JSON response on UI.
JS parse the Integer value incorrectly if the Integer length is over 16.

We can reproduce this bug in Chrome Dev Tool

// # Integer with 16 length
console.log(1234567890123456); 
// Output: 1234567890123456 => OK

// # Integer with 17 length
console.log(12345678901234567);
// Output: 12345678901234568 => WTF ... JS ??? 

// # Integer with 19 length
console.log(1234567890123456789);
// Output: 1234567890123456800 => LOL ??? 

Everyone in the team was WTF ?

How to fix

This bug should be fixed on Backend side, it would be much easier to handle.

Backend API instead of response JSON like this:

{
  "token": 9857754216548798231,
  "seed": 778981355798746677
}

We should convert the value into String

{
  "token": "9857754216548798231",
  "seed": "778981355798746677"
}

Now Frontend team can show it correctly on UI.

To avoid this problem in future, I recommend when building API, all attributes/values JSON in response should be convert into String, not other data type.

Thanks for reading !

Share this on: