DEV Community

Cover image for Universe will collapse before you need BIGINT for milliseconds in JavaScript
Alex Blokh
Alex Blokh

Posted on • Originally published at

Universe will collapse before you need BIGINT for milliseconds in JavaScript

In SQL databases you can store whole numbers in primarily as SMALLINT 2¹⁵-1, INTEGER 2³¹-1 and BIGINT 2⁶³-1, always wondered why not just INT🧐. SMALLINT is too small, INTEGER for milliseconds is just 49.7 days, so we're left with BIGINT and here come the tricky part - JavaScript numbers.

The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent integers between -2⁵³+1 and 2⁵³–1.
For larger integers, consider using BigInt.

Who likes bigint in JS? You have to transform numbers to bigints before you can operate with them, you can't just pass bigint to an API JSON response, they're tricky. Those are exact problems my teammate faced on the project recently. So what to do?

We can assume that we'll never surpass a 2⁵³ milliseconds in any foreseeable future. I was roughly calculating with him on the phone call and I was under impression it's going to be more than a lifespan of the universe, which is ~13.4 billion years, but when I got to the keyboard I've found out that it's just 285 427 years. This number it's that dramatic, but it's more than enough to let people of the future debug the code searching for why your service messes up dates on the webpage.

That is exactly why we created a configuration for bigints and bigserials in DrizzleORM so you can automatically enjoy the numbers-land

bigserial("will_be_number", maxBytes: "max_bytes_53");
bigserial("will_be_bigint", maxBytes: "max_bytes_64");
Enter fullscreen mode Exit fullscreen mode


Top comments (0)