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
numberin arithmetic:1n + 1throws aTypeError. Convert explicitly withBigInt(x)orNumber(big)(which may lose precision). - Division truncates towards zero:
7n / 2n === 3n. - Comparisons work across types:
1n < 2istrue,1n == 1istrue,1n === 1isfalse. Mathfunctions do not accept BigInt.typeof 10nis"bigint".JSON.stringifythrows on BigInt; convert to a string first (or defineBigInt.prototype.toJSONin your app, carefully).- No unary
+(+1nthrows).
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
1console.log(Number.MAX_SAFE_INTEGER); // 90071992547409912console.log(9007199254740993); // 9007199254740992 <- precision silently lost3console.log(9007199254740993n); // 9007199254740993n - exact45// Big factorials stay exact6const factorial = (n) => (n <= 1n ? 1n : n * factorial(n - 1n));7console.log(factorial(25n)); // 15511210043330985984000000n89// Cannot mix with number10try {11 console.log(10n + 1);12} catch (e) {13 console.log(e.name); // TypeError14}15console.log(10n + BigInt(1), Number(10n) + 1); // 11n 111617console.log(7n / 2n, 1n < 2, 1n == 1, 1n === 1); // 3n true true false1819// JSON: send large ids as strings20const 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.