What is BigInt?

BigInt is a numeric primitive for integers of any size, written with an n suffix (123n) or created with BigInt(value); it exists because regular numbers lose precision beyond Number.MAX_SAFE_INTEGER (2^53 - 1).

Why it is needed

number is a 64-bit float and represents every integer exactly only up to 9,007,199,254,740,991. Beyond that, 9007199254740993 silently becomes 9007199254740992. That breaks database ids (Twitter/X, Discord snowflakes), financial calculations in minor units, cryptography and high-precision timestamps.

Rules

  • No mixing with number in arithmetic: 1n + 1 throws a TypeError. Convert explicitly with BigInt(x) or Number(big) (which may lose precision).
  • Division truncates towards zero: 7n / 2n === 3n.
  • Comparisons work across types: 1n < 2 is true, 1n == 1 is true, 1n === 1 is false.
  • Math functions do not accept BigInt.
  • typeof 10n is "bigint".
  • JSON.stringify throws on BigInt; convert to a string first (or define BigInt.prototype.toJSON in your app, carefully).
  • No unary + (+1n throws).

When to use it

  • Large integer ids from APIs: keep them as strings in JSON, convert to BigInt only for arithmetic.
  • Exact integer arithmetic beyond 2^53.

When not to

Decimals (BigInt is integers only) and ordinary counters: BigInt is slower than number. For money, store integer cents (a number is fine up to large amounts) or use a decimal library.

Code example

js
1console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
2console.log(9007199254740993); // 9007199254740992 <- precision silently lost
3console.log(9007199254740993n); // 9007199254740993n - exact
4
5// Big factorials stay exact
6const factorial = (n) => (n <= 1n ? 1n : n * factorial(n - 1n));
7console.log(factorial(25n)); // 15511210043330985984000000n
8
9// Cannot mix with number
10try {
11 console.log(10n + 1);
12} catch (e) {
13 console.log(e.name); // TypeError
14}
15console.log(10n + BigInt(1), Number(10n) + 1); // 11n 11
16
17console.log(7n / 2n, 1n < 2, 1n == 1, 1n === 1); // 3n true true false
18
19// JSON: send large ids as strings
20const order = { id: 1234567890123456789n, total: 4999 };
21const json = JSON.stringify(order, (k, v) => (typeof v === "bigint" ? v.toString() : v));
22console.log(json); // {"id":"1234567890123456789","total":4999}
23console.log(BigInt(JSON.parse(json).id) + 1n); // 1234567890123456790n

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app