Ordinary numbers are exact only up to Number.MAX_SAFE_INTEGER, which is 9,007,199,254,740,991. BigInt is a separate type that stores whole numbers exactly, however large they are.
Creating a BigInt
Add n to the end of an integer, or call BigInt().
const big = 12345678901234567890n;
const fromNumber = BigInt(500);
const fromString = BigInt("9007199254740993");
console.log(big); // → 12345678901234567890n
console.log(fromNumber); // → 500n
console.log(fromString); // → 9007199254740993n
Why it matters
console.log(2 ** 53 + 1); // → 9007199254740992 (off by one)
console.log(2n ** 53n + 1n); // → 9007199254740993n (exact)
Rules
BigInt supports the usual maths operators, but only with other BigInts.
console.log(100n * 3n); // → 300n
console.log(10n / 3n); // → 3n (no decimals)
console.log(10n % 3n); // → 1n
console.log(5n > 3); // → true (comparing is allowed)
console.log(5n + 1); // error on purpose: cannot mix BigInt and Number
- Division rounds down to a whole number.
- You cannot mix BigInt and Number in arithmetic. Convert with
BigInt(x)orNumber(x). Mathfunctions do not work with BigInt.JSON.stringifythrows on a BigInt. Convert it to a string first.
When to use it
- IDs that are bigger than 2⁵³ (some APIs return them as strings for this reason).
- Exact whole-number maths in finance or cryptography-style calculations.
For normal counting, prices in cents, array lengths and everything else, regular numbers are the right choice. BigInt is a tool for specific jobs, not a replacement.