BigInt: exact integers beyond 2^53 (ES2020)
What you’ll learn
Section titled “What you’ll learn”- Why
Numbersilently corrupts integers above 2^53 − 1, and how BigInt fixes that. - Which operators accept BigInts, and the errors you get when you mix them with numbers.
- How to read and write 64-bit IDs in JSON without losing digits, and decode bit fields.
- When BigInt is the wrong tool.
Summary
Section titled “Summary”TL;DR: BigInt is a primitive type for integers of arbitrary size. Write it with an n suffix (42n) or call BigInt(value). Arithmetic on BigInts is exact, but BigInt and Number never mix in arithmetic: you convert explicitly. typeof 42n is "bigint".
It was added in ECMAScript 2020 and is supported by every current browser and server runtime (details in Compatibility).
The problem it solves
Section titled “The problem it solves”A JavaScript number is an IEEE 754 double. It represents every integer exactly only up to Number.MAX_SAFE_INTEGER (2^53 − 1, 9,007,199,254,740,991). Above that, neighboring integers collapse into the same value, and nothing warns you.
That matters as soon as a system hands you 64-bit integers: database BIGINT keys, snowflake-style IDs or nanosecond timestamps. In the OrdersPortal app used on this page, order IDs come from a 64-bit ID service.
Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). All outputs shown were produced with Node.js 22.23.
// Before: an OrdersPortal order ID from a 64-bit ID service, parsed as a Number.const payload = '{"orderId": 9007199254740993, "item": "keyboard"}';const asNumber = JSON.parse(payload).orderId;console.log(asNumber); // the ID has silently changedconsole.log(Number.isSafeInteger(asNumber)); // falseconsole.log(2 ** 53 === 2 ** 53 + 1); // true: Number cannot tell them apart
// After: BigInt keeps every digit.const asBigInt = 9007199254740993n;console.log(asBigInt); // 9007199254740993nconsole.log(asBigInt + 1n); // 9007199254740994nconsole.log(2n ** 53n === 2n ** 53n + 1n); // falseOutput:
9007199254740992falsetrue9007199254740993n9007199254740994nfalseThe parsed ID ends in 2, not 3: a different order. Before ES2020 the fixes were keeping IDs as strings or a userland library such as JSBI.
How it works
Section titled “How it works”Creating and using BigInts
Section titled “Creating and using BigInts”// Creating BigIntsconsole.log(42n, BigInt(42), BigInt('9007199254740993'), BigInt('0xff'), BigInt(true));console.log(typeof 42n); // 'bigint'
// Arithmetic stays in BigInt; division truncates toward zeroconsole.log(7n / 2n, -7n / 2n, 7n % 2n, 2n ** 64n);
// Equality and comparison may mix types; arithmetic may notconsole.log(1n == 1, 1n === 1, 2n > 1);console.log([3n, 1, 2n].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)));
const attempts = [ () => 1n + 1, () => +1n, () => Math.max(1n, 2n), () => BigInt(1.5), () => BigInt('1.5'), () => 2n ** -1n, () => 1n / 0n, () => new BigInt(1), () => JSON.stringify({ id: 1n }), () => 1n >>> 0n,];for (const fn of attempts) { try { console.log(fn()); } catch (e) { console.log(fn.toString().slice(6).padEnd(27), e.constructor.name); }}
// Explicit conversionsconsole.log(Number(2n ** 64n), String(10n), 10n.toString(16));console.log(BigInt(Number.MAX_SAFE_INTEGER) + 2n);// Fixed-width wrappingconsole.log(BigInt.asUintN(64, -1n), BigInt.asIntN(8, 255n));console.log(Boolean(0n), `${0n ? 'truthy' : 'falsy'}`);Output:
42n 42n 9007199254740993n 255n 1nbigint3n -3n 1n 18446744073709551616ntrue false true[ 1, 2n, 3n ]1n + 1 TypeError+1n TypeErrorMath.max(1n, 2n) TypeErrorBigInt(1.5) RangeErrorBigInt('1.5') SyntaxError2n ** -1n RangeError1n / 0n RangeErrornew BigInt(1) TypeErrorJSON.stringify({ id: 1n }) TypeError1n >>> 0n TypeError18446744073709552000 10 a9007199254740993n18446744073709551615n -1nfalse falsyThe rules behind that output:
- Creation. A literal is an integer followed by
n. It can use the0x,0oand0bprefixes (see Octal and binary literals) and numeric separators, but not a decimal point, an exponent, or a leading zero (0755nis aSyntaxError).BigInt()is called withoutnew; it accepts integers, integer strings and booleans. - No implicit mixing.
+,-,*,/,%,**, the bitwise operators and++/--require both operands to be BigInt, otherwise they throw aTypeError. The spec does this on purpose: any automatic conversion would lose either precision or the fraction. The exception is+with a string, which concatenates. - Comparisons do mix.
<,>,<=,>=and==compare the mathematical values, so1n == 1istrueand2n > 1istrue.1n === 1isfalsebecause the types differ. - Integer division.
/truncates toward zero, and dividing by0nthrows aRangeErrorinstead of returningInfinity. A negative exponent also throws, because the result would not be an integer. - Not supported: unary
+(kept out so asm.js code that relies on+xmeaning “number” keeps working),>>>(BigInts have no fixed width, so “unsigned” has no meaning) and everyMathmethod. - Conversions are explicit and can be lossy.
BigInt(1.5)throws rather than rounding.Number(big)rounds to the nearest double, which is how2n ** 64nbecame18446744073709552000. - Fixed-width results.
BigInt.asUintN(bits, x)andBigInt.asIntN(bits, x)wrap a value to an unsigned or signedbits-wide integer, which is how you emulate 64-bit integer overflow from other languages. - Truthiness. Only
0nis falsy.
BigInt also works with BigInt64Array, BigUint64Array and DataView.prototype.getBigInt64() for binary data, and the two BigInt typed arrays can be used with Atomics (see Shared memory). The exponent operator works on BigInts too; see Exponentiation operator.
Realistic example
Section titled “Realistic example”OrdersPortal receives order IDs as JSON numbers from its 64-bit ID service. Each ID packs a creation time, a worker number and a sequence number into one integer. The module below reads the JSON without losing digits, decodes the fields, sums a ledger exactly, and writes BigInts back as plain JSON numbers.
It relies on JSON.parse source text access, part of ECMAScript 2026: the reviver’s third context argument exposes the original text of each primitive, and JSON.rawJSON() emits raw JSON text. That needs Node.js 21+, Chrome 114+, Firefox 135+ or Safari 18.4+; on older runtimes, send large IDs as strings instead.
// orders-ids.mjs - OrdersPortal: 64-bit order IDs and ledger totals with BigInt.const EPOCH_MS = 1_704_067_200_000n; // 2024-01-01T00:00:00Z, the ID service's custom epoch
// Layout (63 bits used): 41 bits milliseconds since EPOCH_MS | 10 bits worker | 12 bits sequenceexport function encodeOrderId(createdAtMs, worker, sequence) { return ((BigInt(createdAtMs) - EPOCH_MS) << 22n) | (BigInt(worker) << 12n) | BigInt(sequence);}
export function decodeOrderId(id) { return { createdAt: new Date(Number((id >> 22n) + EPOCH_MS)).toISOString(), worker: Number((id >> 12n) & 0x3ffn), sequence: Number(id & 0xfffn), };}
// Read: convert the original source text, so large integers never pass through Number.export function parseOrders(json) { return JSON.parse(json, (key, value, context) => key === 'id' || key === 'totalCents' ? BigInt(context.source) : value);}
// Write: emit BigInts as plain JSON numbers.export function stringifyOrders(data) { return JSON.stringify(data, (key, value) => typeof value === 'bigint' ? JSON.rawJSON(value.toString()) : value);}
export function formatCents(cents) { const sign = cents < 0n ? '-' : ''; const abs = cents < 0n ? -cents : cents; return `${sign}$${(abs / 100n).toLocaleString('en-US')}.${String(abs % 100n).padStart(2, '0')}`;}
const id = encodeOrderId(Date.UTC(2026, 10, 18, 9, 30), 17, 42);console.log(id, Number.isSafeInteger(Number(id)));console.log(decodeOrderId(id));
const body = `[{"id": ${id}, "totalCents": 4599}, {"id": ${id + 1n}, "totalCents": 9007199254740993}]`;const orders = parseOrders(body);console.log(orders.map((o) => o.id - id)); // exact, because no digit was lost
const ledger = orders.reduce((sum, o) => sum + o.totalCents, 0n);console.log(formatCents(ledger));console.log(stringifyOrders({ ledger, count: orders.length }));Output:
381375479808069674n false{ createdAt: '2026-11-18T09:30:00.000Z', worker: 17, sequence: 42 }[ 0n, 1n ]$90,071,992,547,455.92{"ledger":9007199254745592,"count":2}Convert at the boundary (parse and serialize) so the rest of the module sees one numeric type, keep money in integer minor units (cents), and convert to Number only for values you know are small, such as the 10-bit worker field. toLocaleString and Intl.NumberFormat accept BigInts directly.
Common mistakes
Section titled “Common mistakes”- Parsing first, converting later.
BigInt(JSON.parse(text).id)is too late:JSON.parsealready rounded the number. Use the reviver’scontext.source, or have the API send the ID as a string. BigInt(someLargeNumber).BigInt(9007199254740993)gives9007199254740992n, because the literal was rounded to a double beforeBigIntsaw it. Pass a string or write a BigInt literal.- Using
/for money with fractions.500n / 3nis166n; the remainder disappears. Decide on a rounding rule and apply it with%, or use a decimal library. - Sorting with
(a, b) => a - b. It throws even when every element is a BigInt: the comparator returns a BigInt, andsortconverts the result to a Number, which is aTypeError. On mixed arrays the subtraction itself throws. Usea < b ? -1 : a > b ? 1 : 0. - Patching
BigInt.prototype.toJSON. It changesJSON.stringifyfor the whole process, including libraries. Prefer a replacer at your own boundary. - Assuming
Mathworks.Math.max,Math.absandMath.powthrow for BigInts. Use comparisons,x < 0n ? -x : xand**. - Cryptography. BigInt operations are not constant-time, so their timing can leak secret values. Use the Web Crypto API.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Use | Why |
|---|---|---|
| Integers that stay below 2^53 (counts, indexes, most IDs) | Number |
Faster, works with Math, JSON and every API |
64-bit IDs, database BIGINT, nanosecond timestamps |
BigInt |
Exact at any size |
| IDs you only store and compare, never compute with | string |
No conversion, survives any JSON parser |
| Money with fractions, tax and rounding rules | Integer minor units in BigInt or Number, or a decimal library |
BigInt has no fractions |
| Bit fields wider than 32 bits | BigInt |
Number’s bitwise operators truncate to 32 bits |
| Hot numeric loops | Number |
BigInt arithmetic is much slower in current engines |
On the performance point: summing the integers below ten million took about 64 ms with Number and about 281 ms with BigInt in one Node.js 22.23 run. Treat that as an order of magnitude, not a benchmark, and measure your own workload.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, BigInt is supported in Chrome 67, Edge 79, Firefox 68, Safari 14 (including iOS), Node.js 10.4.0, Deno 1.0 and Bun 1.0; Safari added BigInt64Array, BigUint64Array and the DataView BigInt methods in 15. Internet Explorer never supported BigInt.
The JSON source text access used in the realistic example (context.source, JSON.rawJSON) is ES2026 and needs Chrome and Edge 114, Firefox 135, Safari 18.4, Node.js 21.0, Deno 1.33 or Bun 1.1.43.
TypeScript: the type is bigint (lowercase). BigInt literals require target ES2020 or later; with an older target, TypeScript 6.0 reports TS2737: BigInt literals are not available when targeting lower than ES2020.
Polyfills: none are possible: a polyfill cannot add a primitive type or overload +, and transpilers cannot rewrite 10n.
Interview questions
Section titled “Interview questions”1. Why does JSON.parse('{"id": 9007199254740993}').id return a different number?
JSON numbers become IEEE 754 doubles, which are exact only up to 2^53 − 1. The value is rounded to the nearest representable double, 9007199254740992. Fix it at parse time with the reviver’s context.source and BigInt(), or send the ID as a string.
2. Why does 1n + 1 throw, while 1n < 2 works?
Arithmetic must produce a value of one type, and converting either way can lose information: a BigInt can exceed Number’s precision, and a Number can have a fraction. Comparisons only produce a boolean, so the spec compares the mathematical values directly.
3. What is -7n / 2n, and what is BigInt(1.5)?
-3n: BigInt division truncates toward zero. BigInt(1.5) throws a RangeError, because BigInt refuses to round implicitly; call Math.trunc or Math.round first if rounding is what you want.
4. Senior scenario: your Node.js service talks to a Java service whose IDs are 64-bit long values, and some front-end clients run on browsers without JSON source access. How do you design the contract?
Make IDs strings on the wire ("id": "381375479808069674"), which every JSON parser preserves. Convert to BigInt only where the service computes with IDs, such as decoding bit fields, and keep them opaque strings in the UI. Add a schema check that rejects numeric IDs above Number.MAX_SAFE_INTEGER, so a producer that switches back to numbers fails loudly. context.source and JSON.rawJSON allow numeric JSON when every client supports them, but strings are the safer contract.
Key takeaways
Section titled “Key takeaways”- BigInt (ES2020) gives exact integers of any size:
123norBigInt(value). - BigInt and Number never mix in arithmetic; convert explicitly at your boundaries.
- Division truncates, and
Math, unary+andJSON.stringifyreject BigInts. - JSON loses large numbers unless you read
context.source(ES2026) or send strings. - Use Number by default; use BigInt when values can exceed 2^53 − 1.
Related pages
Section titled “Related pages”- Exponentiation operator:
**, the one way to raise a BigInt to a power. - Octal and binary literals: the
0b,0oand0xprefixes that BigInt literals also accept. - Numeric separators:
1_000_000nfor readable large literals. - Shared memory:
BigInt64ArraywithAtomicsacross workers. - Math object: the Number-only helpers that BigInt cannot use.
- Type coercion: how
==and+convert values, including BigInts. - JavaScript interview questions
Official references
Section titled “Official references”- ECMAScript Language Specification, BigInt Objects (current draft; first published in ECMAScript 2020, 11th edition)
- ECMAScript 2020 Language Specification (ECMA-262, 11th edition), BigInt Objects
- ECMAScript Language Specification,
JSON.rawJSON(ECMAScript 2026) - TC39 proposal: BigInt
- TC39 proposal: JSON.parse source text access
- MDN: BigInt
- MDN: JSON.rawJSON()