BigInt

Updated · 6 min read
easyES2026javascriptbigintnumberses2020

BigInt is a primitive type used to represent whole numbers of any size, exactly. Ordinary numbers lose precision above 2⁵³ − 1 (about 9 quadrillion), which is a real problem for 64-bit database IDs, cryptography, high-precision timestamps and some financial totals. A BigInt never loses a digit; the trade-offs are that it holds only whole numbers and doesn't mix freely with ordinary numbers.

In One Minute

  • Create a BigInt by adding n to an integer (9007199254740993n) or with BigInt("9007199254740993").
  • Arithmetic works as usual, except that / drops the fractional part: 7n / 2n is 3n.
  • You can't mix BigInt and number in arithmetic (1n + 1 is a TypeError). Convert one side explicitly.
  • Comparisons do work across types: 1n < 2 is true, 1n == 1 is true, 1n === 1 is false.
  • JSON.stringify throws on BigInt; send big IDs as strings.

Creating BigInts

create.js▶ Try it
const big = 9007199254740993n;
const fromString = BigInt("9007199254740993");
const fromNumber = BigInt(42);
 
console.log(typeof big);
console.log(big === fromString);
console.log(fromNumber);
console.log(String(big));
console.log(9007199254740993);
Output
bigint
true
42
9007199254740993
9007199254740992

Explanation: the BigInt keeps the exact value. The plain number on the last line is silently rounded to ...992, because it is beyond the safe integer range. (This site's console shows BigInts without the n; the browser console and Node.js show 9007199254740993n.)

Arithmetic Rules

All the usual operators work, as long as both sides are BigInts:

arithmetic.js▶ Try it
const a = 10n;
const b = 3n;
 
console.log(String(a + b), String(a - b), String(a * b));
console.log(String(a / b));
console.log(String(a % b));
console.log(String(2n ** 64n));
console.log(String(-7n / 2n));
Output
13 7 30
3
1
18446744073709551616
-3

Explanation: division rounds toward zero, so 10n / 3n is 3n and -7n / 2n is -3n. 2n ** 64n shows the point of BigInt: a 20-digit number, exact. The unary plus (+10n) is a TypeError, because +x means "convert to number", which would lose precision silently.

No Mixing with Numbers

mixing.js▶ Try it
try {
  console.log(10n + 5);
} catch (err) {
  console.log(err.name + ": " + err.message);
}
 
console.log(String(10n + BigInt(5)));
console.log(Number(10n) + 5);
Output
TypeError: Cannot mix BigInt and other types, use explicit conversions
15
15

JavaScript refuses to mix them because neither type can represent every value of the other: numbers have decimals, and BigInts have digits beyond 2⁵³. Making you convert explicitly means you decide where precision might be lost. The try...catch used here to show the error has its own lesson in the errors chapter.

Comparisons

Comparing across the two types is allowed, because no precision is at risk:

compare.js▶ Try it
console.log(1n < 2);
console.log(2n > 1.5);
console.log(1n == 1);
console.log(1n === 1);
console.log(0n ? "truthy" : "falsy");
Output
true
true
true
false
falsy

1n === 1 is false because the types differ. 0n is falsy, like 0.

OperationBigInt with BigIntBigInt with number
+ - * / % **YesTypeError
< > <= >=YesYes
==YesYes (by value)
===YesAlways false
Math.max, Math.round...TypeErrorn/a

BigInt and JSON

JSON.stringify doesn't know how to write a BigInt and throws. The common solution, used by most APIs, is to send large IDs as strings:

json.js▶ Try it
const payment = { id: 9007199254740993n, amount: 120 };
 
try {
  JSON.stringify(payment);
} catch (err) {
  console.log(err.name + ": " + err.message);
}
 
const json = JSON.stringify(payment, (key, value) =>
  typeof value === "bigint" ? value.toString() : value
);
console.log(json);
Output
TypeError: Do not know how to serialize a BigInt
{"id":"9007199254740993","amount":120}

The second argument to JSON.stringify is a replacer function that can change values on the way out; the JSON lesson covers it.

When to Use BigInt

Use BigIntDon't use BigInt
64-bit IDs from databases (when you need to do math on them)Ordinary counts, prices in cents, scores
Cryptography and hashing mathAnything with decimals
Nanosecond timestamps (process.hrtime.bigint() in Node.js)Hot loops where speed matters (BigInt math is slower)
Exact factorials and combinatoricsValues passed to Math functions

For money, integer cents in a normal number are exact up to $90 trillion. You need BigInt only for amounts beyond that, or for very fine fractions of a cent stored as integers.

In Practice

The Fee Tracker receives 64-bit payment IDs from a server as strings, and needs the next ID in a sequence. A plain number would get it wrong; BigInt gets it right:

next-id.js▶ Try it
const lastId = "9007199254740993";
 
console.log(String(Number(lastId) + 1));
console.log(String(BigInt(lastId) + 1n));
Output
9007199254740992
9007199254740994

The number version is wrong: Number("9007199254740993") silently becomes ...992, and adding 1 to it can't be represented either, so the result rounds back down to ...992, the same value as before the "increment". Try the next ID up:

next-id-2.js▶ Try it
const lastId = "9007199254740994";
 
console.log(String(Number(lastId) + 1));
console.log(String(BigInt(lastId) + 1n));
Output
9007199254740996
9007199254740995

This time the number version skips an ID entirely. Above the safe limit, plain numbers can repeat or skip values; BigInt is exact every time.

Common Mistakes

Mixing types. bigValue + 1 throws. Use bigValue + 1n.

Creating BigInts from large numbers. The number is already rounded. Use a string or an n literal.

Expecting decimals from division. 5n / 2n is 2n. Use numbers for fractional results.

Sending BigInts in JSON. Convert to strings with a replacer, or call .toString() yourself.

Practice

Challenge: Write factorial(n) that returns the exact factorial of a whole number as a BigInt, and print factorial(25) as a string.

Show solution
factorial.js▶ Try it
function factorial(n) {
  let result = 1n;
  for (let i = 2n; i <= BigInt(n); i++) {
    result *= i;
  }
  return result;
}
 
console.log(String(factorial(5)));
console.log(String(factorial(25)));
Output
120
15511210043330985984000000

Quick check: BigInt

3 questions
1What is 7n / 2n?
2What happens with 10n + 1?
3What is 1n === 1?

Key Takeaways

TaskCode
Create123n, BigInt("123")
Convert to numberNumber(big) (may lose precision)
Convert to stringbig.toString()
Check the typetypeof x === "bigint"

Was this tutorial helpful?

Lesson 25 of 139