JavaScript BigInt

Whole Numbers Without Limits

JavaScript BigInt

When `number` isn't big enough — `BigInt` lets you work with integers of arbitrary size. Reach for it when precision matters.

4 min read Level 2/5 #bigint#numbers#integers
What you'll learn
  • Write `BigInt` literals with the `n` suffix
  • Know when ordinary numbers stop being accurate
  • Avoid mixing `BigInt` and `Number` in math

Regular number values stop being accurate above Number.MAX_SAFE_INTEGER (about 9 quadrillion). For most apps, that’s plenty. For database IDs, cryptography, or scientific computing, it’s not enough — and that’s where BigInt comes in.

Creating a BigInt

Add an n suffix to an integer literal, or call BigInt(value).

BigInt literals script.js
const big = 9007199254740993n;    // ← n makes it BigInt
const veryBig = 12345678901234567890n;

console.log(big);                  // 9007199254740993n
console.log(typeof big);           // "bigint"

const fromString = BigInt("12345"); // also works
console.log(fromString);            // 12345n
▶ Preview: console

When You Need It

Compare ordinary number vs BigInt for the same large integer:

Why BigInt exists script.js
console.log(9007199254740993);     // 9007199254740992 ❌ rounded
console.log(9007199254740993n);    // 9007199254740993n ✅ exact
▶ Preview: console

If you’re working with:

  • Database IDs beyond 2^53
  • Timestamps in nanoseconds
  • Cryptographic numbers
  • Counts where every unit matters (financial reconciliation)

…use BigInt.

Math Works the Same Way

The usual operators work on BigInt — but only with other BigInts.

BigInt math script.js
const a = 1000000000000n;
const b = 2000000000000n;

console.log(a + b);   // 3000000000000n
console.log(a * b);   // 2000000000000000000000000n
console.log(b / a);   // 2n  ← integer division (no decimals)
console.log(b % a);   // 0n
▶ Preview: console
The mixing error script.js
const big = 100n;
const small = 5;

// console.log(big + small); // TypeError: Cannot mix BigInt and other types

console.log(big + BigInt(small));     // 105n
console.log(Number(big) + small);     // 105   (back to regular number)
▶ Preview: console

Comparison Works Loosely

BigInt and Number can be compared with ===, <, >, etc. — just not added or multiplied together.

Comparison script.js
console.log(10n === 10);    // false  ← different types
console.log(10n == 10);     // true   ← loose equality converts
console.log(10n < 20);      // true   ← comparison works
▶ Preview: console

When NOT to Use BigInt

  • DecimalsBigInt is integer-only. 100n / 3n gives 33n, not 33.33.
  • Performance-critical mathBigInt operations are slower than regular number.
  • When Number.MAX_SAFE_INTEGER is enough — most of the time, it is.

Up Next

The last primitive type for a while — booleans.

JavaScript Booleans →