BigInt
BigInt is a primitive type used to represent whole numbers of any size, exactly. Ordinary numbers lose precision above 2⁵³ − 1 (about 9 quadrillion), which is a real problem for 64-bit database IDs, cryptography, high-precision timestamps and some financial totals. A BigInt never loses a digit; the trade-offs are that it holds only whole numbers and doesn't mix freely with ordinary numbers.
In One Minute
- Create a BigInt by adding
nto an integer (9007199254740993n) or withBigInt("9007199254740993"). - Arithmetic works as usual, except that
/drops the fractional part:7n / 2nis3n. - You can't mix BigInt and number in arithmetic (
1n + 1is aTypeError). Convert one side explicitly. - Comparisons do work across types:
1n < 2istrue,1n == 1istrue,1n === 1isfalse. JSON.stringifythrows on BigInt; send big IDs as strings.
Creating BigInts
const big = 9007199254740993n;
const fromString = BigInt("9007199254740993");
const fromNumber = BigInt(42);
console.log(typeof big);
console.log(big === fromString);
console.log(fromNumber);
console.log(String(big));
console.log(9007199254740993);bigint
true
42
9007199254740993
9007199254740992Explanation: the BigInt keeps the exact value. The plain number on the last line is silently rounded to ...992, because it is beyond the safe integer range. (This site's console shows BigInts without the n; the browser console and Node.js show 9007199254740993n.)
Arithmetic Rules
All the usual operators work, as long as both sides are BigInts:
const a = 10n;
const b = 3n;
console.log(String(a + b), String(a - b), String(a * b));
console.log(String(a / b));
console.log(String(a % b));
console.log(String(2n ** 64n));
console.log(String(-7n / 2n));13 7 30
3
1
18446744073709551616
-3Explanation: division rounds toward zero, so 10n / 3n is 3n and -7n / 2n is -3n. 2n ** 64n shows the point of BigInt: a 20-digit number, exact. The unary plus (+10n) is a TypeError, because +x means "convert to number", which would lose precision silently.
No Mixing with Numbers
try {
console.log(10n + 5);
} catch (err) {
console.log(err.name + ": " + err.message);
}
console.log(String(10n + BigInt(5)));
console.log(Number(10n) + 5);TypeError: Cannot mix BigInt and other types, use explicit conversions
15
15JavaScript refuses to mix them because neither type can represent every value of the other: numbers have decimals, and BigInts have digits beyond 2⁵³. Making you convert explicitly means you decide where precision might be lost. The try...catch used here to show the error has its own lesson in the errors chapter.
Comparisons
Comparing across the two types is allowed, because no precision is at risk:
console.log(1n < 2);
console.log(2n > 1.5);
console.log(1n == 1);
console.log(1n === 1);
console.log(0n ? "truthy" : "falsy");true
true
true
false
falsy1n === 1 is false because the types differ. 0n is falsy, like 0.
| Operation | BigInt with BigInt | BigInt with number |
|---|---|---|
+ - * / % ** | Yes | TypeError |
< > <= >= | Yes | Yes |
== | Yes | Yes (by value) |
=== | Yes | Always false |
Math.max, Math.round... | TypeError | n/a |
BigInt and JSON
JSON.stringify doesn't know how to write a BigInt and throws. The common solution, used by most APIs, is to send large IDs as strings:
const payment = { id: 9007199254740993n, amount: 120 };
try {
JSON.stringify(payment);
} catch (err) {
console.log(err.name + ": " + err.message);
}
const json = JSON.stringify(payment, (key, value) =>
typeof value === "bigint" ? value.toString() : value
);
console.log(json);TypeError: Do not know how to serialize a BigInt
{"id":"9007199254740993","amount":120}The second argument to JSON.stringify is a replacer function that can change values on the way out; the JSON lesson covers it.
When to Use BigInt
| Use BigInt | Don't use BigInt |
|---|---|
| 64-bit IDs from databases (when you need to do math on them) | Ordinary counts, prices in cents, scores |
| Cryptography and hashing math | Anything with decimals |
Nanosecond timestamps (process.hrtime.bigint() in Node.js) | Hot loops where speed matters (BigInt math is slower) |
| Exact factorials and combinatorics | Values passed to Math functions |
For money, integer cents in a normal number are exact up to $90 trillion. You need BigInt only for amounts beyond that, or for very fine fractions of a cent stored as integers.
In Practice
The Fee Tracker receives 64-bit payment IDs from a server as strings, and needs the next ID in a sequence. A plain number would get it wrong; BigInt gets it right:
const lastId = "9007199254740993";
console.log(String(Number(lastId) + 1));
console.log(String(BigInt(lastId) + 1n));9007199254740992
9007199254740994The number version is wrong: Number("9007199254740993") silently becomes ...992, and adding 1 to it can't be represented either, so the result rounds back down to ...992, the same value as before the "increment". Try the next ID up:
const lastId = "9007199254740994";
console.log(String(Number(lastId) + 1));
console.log(String(BigInt(lastId) + 1n));9007199254740996
9007199254740995This time the number version skips an ID entirely. Above the safe limit, plain numbers can repeat or skip values; BigInt is exact every time.
Common Mistakes
Mixing types. bigValue + 1 throws. Use bigValue + 1n.
Creating BigInts from large numbers. The number is already rounded. Use a string or an n literal.
Expecting decimals from division. 5n / 2n is 2n. Use numbers for fractional results.
Sending BigInts in JSON. Convert to strings with a replacer, or call .toString() yourself.
Practice
Challenge: Write factorial(n) that returns the exact factorial of a whole number as a BigInt, and print factorial(25) as a string.
Show solution
function factorial(n) {
let result = 1n;
for (let i = 2n; i <= BigInt(n); i++) {
result *= i;
}
return result;
}
console.log(String(factorial(5)));
console.log(String(factorial(25)));120
15511210043330985984000000Key Takeaways
| Task | Code |
|---|---|
| Create | 123n, BigInt("123") |
| Convert to number | Number(big) (may lose precision) |
| Convert to string | big.toString() |
| Check the type | typeof x === "bigint" |
Was this tutorial helpful?