Skip to content

BigInt: exact integers beyond 2^53 (ES2020)

  • Why Number silently 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.

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).

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 changed
console.log(Number.isSafeInteger(asNumber)); // false
console.log(2 ** 53 === 2 ** 53 + 1); // true: Number cannot tell them apart
// After: BigInt keeps every digit.
const asBigInt = 9007199254740993n;
console.log(asBigInt); // 9007199254740993n
console.log(asBigInt + 1n); // 9007199254740994n
console.log(2n ** 53n === 2n ** 53n + 1n); // false

Output:

9007199254740992
false
true
9007199254740993n
9007199254740994n
false

The 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.

// Creating BigInts
console.log(42n, BigInt(42), BigInt('9007199254740993'), BigInt('0xff'), BigInt(true));
console.log(typeof 42n); // 'bigint'
// Arithmetic stays in BigInt; division truncates toward zero
console.log(7n / 2n, -7n / 2n, 7n % 2n, 2n ** 64n);
// Equality and comparison may mix types; arithmetic may not
console.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 conversions
console.log(Number(2n ** 64n), String(10n), 10n.toString(16));
console.log(BigInt(Number.MAX_SAFE_INTEGER) + 2n);
// Fixed-width wrapping
console.log(BigInt.asUintN(64, -1n), BigInt.asIntN(8, 255n));
console.log(Boolean(0n), `${0n ? 'truthy' : 'falsy'}`);

Output:

42n 42n 9007199254740993n 255n 1n
bigint
3n -3n 1n 18446744073709551616n
true false true
[ 1, 2n, 3n ]
1n + 1 TypeError
+1n TypeError
Math.max(1n, 2n) TypeError
BigInt(1.5) RangeError
BigInt('1.5') SyntaxError
2n ** -1n RangeError
1n / 0n RangeError
new BigInt(1) TypeError
JSON.stringify({ id: 1n }) TypeError
1n >>> 0n TypeError
18446744073709552000 10 a
9007199254740993n
18446744073709551615n -1n
false falsy

The rules behind that output:

  • Creation. A literal is an integer followed by n. It can use the 0x, 0o and 0b prefixes (see Octal and binary literals) and numeric separators, but not a decimal point, an exponent, or a leading zero (0755n is a SyntaxError). BigInt() is called without new; it accepts integers, integer strings and booleans.
  • No implicit mixing. +, -, *, /, %, **, the bitwise operators and ++/-- require both operands to be BigInt, otherwise they throw a TypeError. 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, so 1n == 1 is true and 2n > 1 is true. 1n === 1 is false because the types differ.
  • Integer division. / truncates toward zero, and dividing by 0n throws a RangeError instead of returning Infinity. 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 +x meaning “number” keeps working), >>> (BigInts have no fixed width, so “unsigned” has no meaning) and every Math method.
  • Conversions are explicit and can be lossy. BigInt(1.5) throws rather than rounding. Number(big) rounds to the nearest double, which is how 2n ** 64n became 18446744073709552000.
  • Fixed-width results. BigInt.asUintN(bits, x) and BigInt.asIntN(bits, x) wrap a value to an unsigned or signed bits-wide integer, which is how you emulate 64-bit integer overflow from other languages.
  • Truthiness. Only 0n is 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.

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 sequence
export 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.

  • Parsing first, converting later. BigInt(JSON.parse(text).id) is too late: JSON.parse already rounded the number. Use the reviver’s context.source, or have the API send the ID as a string.
  • BigInt(someLargeNumber). BigInt(9007199254740993) gives 9007199254740992n, because the literal was rounded to a double before BigInt saw it. Pass a string or write a BigInt literal.
  • Using / for money with fractions. 500n / 3n is 166n; 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, and sort converts the result to a Number, which is a TypeError. On mixed arrays the subtraction itself throws. Use a < b ? -1 : a > b ? 1 : 0.
  • Patching BigInt.prototype.toJSON. It changes JSON.stringify for the whole process, including libraries. Prefer a replacer at your own boundary.
  • Assuming Math works. Math.max, Math.abs and Math.pow throw for BigInts. Use comparisons, x < 0n ? -x : x and **.
  • Cryptography. BigInt operations are not constant-time, so their timing can leak secret values. Use the Web Crypto API.
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.

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.

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.

  • BigInt (ES2020) gives exact integers of any size: 123n or BigInt(value).
  • BigInt and Number never mix in arithmetic; convert explicitly at your boundaries.
  • Division truncates, and Math, unary + and JSON.stringify reject 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.