Skip to content
jshacks.dev
Fundamentals

BigInt in JavaScript for Arbitrary Precision Integers

BigInt holds integers of any size exactly, but it cannot mix with Number, skips Math and fails in JSON. See the rules and when it is worth using.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, Vite, TypeScript and npm logos.

The largest integer a JavaScript number can hold exactly is 9,007,199,254,740,991. Past that, digits silently go missing, which is a poor outcome for a database id, a nanosecond timestamp or an intermediate result in cryptography. BigInt exists for those cases, and it is a separate primitive type with its own arithmetic and its own rules about what it will and will not mix with. This post shows how to create and use one, the places it refuses to cooperate, and how to get one through JSON. All examples run on Node.js 24. The limit it fixes is described in how numbers work in JavaScript, and the type is one of the seven primitives.

Creating and using one

A literal ends in n. BigInt() converts from a number, a string or a boolean, and arithmetic works as for numbers, with exact results.

JavaScript
const big = 2n ** 64n;
const parsed = BigInt("9007199254740993");

console.log(big);
console.log(parsed);
console.log(typeof big);
console.log(Number.MAX_SAFE_INTEGER + 2);
console.log(BigInt(Number.MAX_SAFE_INTEGER) + 2n);
console.log(2 ** 64);
Text
18446744073709551616n
9007199254740993n
bigint
9007199254740992
9007199254740993n
18446744073709552000

Compare the last four lines. Adding 2 to the safe limit as a number gives a wrong, rounded answer, and the bigint version is exact. The number 2 ** 64 prints as 18446744073709552000, with the low digits zeroed. console.log shows a bigint with a trailing n, which is not part of the value.

Conversion has a rule: BigInt() accepts only integers. A fraction is a RangeError, and a string must contain only digits.

JavaScript
for (const input of [1.5, "12.5", "abc", 10]) {
  try {
    console.log(BigInt(input));
  } catch (error) {
    console.log(error.name, error.message);
  }
}
Text
RangeError The number 1.5 cannot be converted to a BigInt because it is not an integer
SyntaxError Cannot convert 12.5 to a BigInt
SyntaxError Cannot convert abc to a BigInt
10n

A number that is not an integer raises RangeError, and a string that does not parse raises SyntaxError. Validate before converting input from a user.

Mixing is an error

Arithmetic between a bigint and a number throws, which is deliberate. Silently converting either way would lose precision or force a rounding choice, so the language makes you pick.

JavaScript
const attempts = [
  () => 1n + 1,
  () => Math.max(1n, 2n),
  () => +1n,
  () => 1n / 0n,
];

for (const attempt of attempts) {
  try {
    attempt();
  } catch (error) {
    console.log(error.name, error.message);
  }
}

console.log(1n + BigInt(1));
console.log(Number(10n) + 1);
Text
TypeError Cannot mix BigInt and other types, use explicit conversions
TypeError Cannot convert a BigInt value to a number
TypeError Cannot convert a BigInt value to a number
RangeError Division by zero
2n
11

Addition with a number throws, Math functions reject bigint arguments, and unary plus throws too. Division by 0n is a RangeError, unlike 1 / 0, which is Infinity. The two explicit conversions at the end show the way through: BigInt() going up and Number() going down, and the second is where precision can be lost for large values.

Comparisons are the exception, and they work across the types by mathematical value.

JavaScript
console.log(1n < 2);
console.log(2n == 2);
console.log(2n === 2);
console.log([3n, 1, 2n, 10].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)));
console.log(0n ? "truthy" : "falsy");
Text
true
true
false
[ 1, 2n, 3n, 10 ]
falsy

Loose equality and relational operators work, strict equality does not because the types differ, and 0n is falsy. Sorting a mixed array needs a comparator that uses < and >, because subtraction would throw.

Division truncates

A bigint has no fractions, so division discards the remainder, rounding toward zero. The remainder comes from %.

JavaScript
console.log(7n / 2n);
console.log(-7n / 2n);
console.log(7n % 2n);
console.log(-7n % 2n);

function divmod(a, b) {
  return [a / b, a % b];
}

console.log(divmod(10n ** 20n + 7n, 10n ** 10n));
Text
3n
-3n
1n
-1n
[ 10000000000n, 7n ]

Truncation toward zero means negative results round up, not down, so -7n / 2n is -3n and the remainder takes the sign of the dividend. If you need floor division for negative values, adjust by hand. A divmod helper keeps both parts in one call.

Fixed-width arithmetic

Hashes, checksums and binary protocols need integers that wrap at a fixed width. BigInt.asUintN() and BigInt.asIntN() reduce a value to the given number of bits.

JavaScript
console.log(BigInt.asUintN(64, -1n));
console.log(BigInt.asUintN(8, 257n));
console.log(BigInt.asIntN(8, 255n));
console.log(BigInt.asIntN(8, 127n));

function fnv1a64(text) {
  let hash = 0xcbf29ce484222325n;
  for (const byte of new TextEncoder().encode(text)) {
    hash ^= BigInt(byte);
    hash = BigInt.asUintN(64, hash * 0x100000001b3n);
  }
  return hash;
}

console.log(fnv1a64("hello").toString(16));
Text
18446744073709551615n
1n
-1n
127n
a430d84680aabd0b

The first four lines show how to reinterpret a value as an unsigned or signed integer of a given width. The fnv1a64 function is the 64-bit FNV-1a hash, a small non-cryptographic hash, and it uses asUintN after each multiplication to keep the result in 64 bits. This is the typical bigint job: fixed-width integer math that would overflow a number.

Getting a bigint through JSON

JSON.stringify() has no representation for it and throws. The usual fix is to send it as a string and convert on the way back.

JavaScript
const record = { id: 9007199254740993n, name: "order" };

try {
  JSON.stringify(record);
} catch (error) {
  console.log(error.name, error.message);
}

const text = JSON.stringify(record, (key, value) =>
  typeof value === "bigint" ? value.toString() : value,
);
console.log(text);

const back = JSON.parse(text, (key, value) =>
  key === "id" ? BigInt(value) : value,
);
console.log(back.id);
Text
TypeError Do not know how to serialize a BigInt
{"id":"9007199254740993","name":"order"}
9007199254740993n

The replacer converted every bigint to a string, and the reviver converted the id field back. Name the fields in the reviver, because converting every numeric-looking string would damage ordinary text. Adding a toJSON method to BigInt.prototype is a global change that other code will inherit, and we avoid it. When the other end is not JavaScript, agree on the string form in the API contract.

Counting with bigint in a loop

Loops are where the type bites first, because the counter, the bound and the arithmetic must all be bigint. A computation that mixes one number in raises the mixing error on the first iteration, which is the benefit of a strict rule: the mistake shows up immediately and not after an hour.

JavaScript
function factorial(n) {
  let result = 1n;
  for (let i = 2n; i <= n; i++) {
    result *= i;
  }
  return result;
}

console.log(factorial(25n));
console.log(factorial(25n).toString().length);
console.log(Number(factorial(25n)));
console.log(factorial(0n));
Text
15511210043330985984000000n
26
1.5511210043330986e+25
1n

The loop variable i starts as 2n and increments with ++, which works on a bigint. The result has 26 digits, all exact. Converting it to a number at the end loses the low digits and prints in exponent form, so convert only for display, and never convert back. If a calculation grows into thousands of digits, remember that each multiplication costs more than the last, and that bigint arithmetic is not constant time, so a loop that looked instant at 25 may take seconds at 25,000.

When to use bigint, and when not to

Use it for integers that can exceed 2^53 - 1: database ids from systems that issue 64-bit values, timestamps in nanoseconds, token amounts with 18 decimals, and intermediate values in number theory. Use number for everything else, because bigint cannot use Math, JSON or most libraries without conversion.

Two cautions apply. It is not faster, and for small values a number is quicker, so do not switch for speed. And a bigint is no help for decimals: 0.1n is a syntax error, and money with fractional units needs integer cents or a decimal library, as in the post on 0.1 plus 0.2.

For formatting, toLocaleString() adds separators, and toString(radix) converts to hex or binary, which suits ids and hashes.

JavaScript
console.log((1234567890123456789n).toLocaleString("en-US"));
console.log((255n).toString(2));
console.log(BigInt(0x7fffffff) + 1n);
Text
1,234,567,890,123,456,789
11111111
2147483648n

What we check in review

When a pull request introduces bigint, we ask four things. Where does the value come from, and can it really exceed 2^53 - 1, or is the type being used out of habit? Where does it leave the program, and how does it cross JSON, a database driver or a log line? Are all conversions explicit and placed at the edges, with none in the middle of a calculation? And is there a test with a value slightly past the safe limit, since a test with small numbers passes whether the type is right or wrong? If a change cannot answer the first question, the type is probably unnecessary and a number or a string would be simpler.

Where this advice stops

Browsers support bigint in every current release, and Node.js has since version 10.4. A runtime without it fails at parse time on the n suffix, so a library that must run in old environments cannot use literals. TypeScript supports it when the target is ES2020 or later, with the bigint type, and rejects mixing at compile time, which catches the TypeError cases before they run.

The type is defined in the specification under the BigInt type, and MDN's page for BigInt documents the constructor and the static methods.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.