Lesson

JS BigInt

10 min reading
Free Course

JavaScript BigInt: Exact Math for Huge Integers

JavaScript BigInt represents whole integers of arbitrary size beyond Number.MAX_SAFE_INTEGER (9,007,199,254,740,991). You create a BigInt by appending n to an integer literal or calling BigInt("...") on a numeric string.

Why Number Fails on Huge Integers

Regular JavaScript numbers lose accuracy past 16 digits. For example, 9007199254740992 + 1 still evaluates to 9007199254740992 because the mantissa runs out of precision bits. That silent rounding breaks 64-bit database IDs, Snowflake tokens, and financial ledger satoshis.

BigInt solves this problem by expanding dynamically in memory to fit integers of almost any length. Comparison operators like >, <, and == still work cleanly between BigInt and Number values when checking thresholds.

Working with BigInt Safely

Notice that BigInt supports +, -, *, **, %, and integer division / (which drops fractional remainders toward zero).

// Pass huge numbers as strings to BigInt() so JS doesn't round them first
const invoiceId = BigInt("9007199254740995123");
const nextId = invoiceId + 1n;

console.log("Original:", invoiceId.toString());
console.log("Next ID: ", nextId.toString());

// Division truncates toward zero
console.log("7n / 2n =", 7n / 2n); // 3n

// Compare BigInt and Number with == or explicit conversion
console.log("Equal value:", 10n === BigInt(10)); // true

Common Mistakes to Avoid

  • Mixing BigInt and Number in math: Writing 10n + 5 throws a TypeError: Cannot mix BigInt and other types. Convert one side explicitly first.
  • Passing a huge literal without quotes to BigInt(): BigInt(9007199254740999) rounds the number before BigInt() receives it. Always pass "9007199254740999" as a string or write 9007199254740999n.
  • Calling JSON.stringify() directly on a BigInt: JSON.stringify({ id: 10n }) throws a TypeError. Convert BigInt fields with .toString() before serializing.

Frequently Asked Questions

Can BigInt store decimal numbers?

No, BigInt supports whole integers only. Passing "3.14" to BigInt("3.14") throws a SyntaxError.

Can I pass a BigInt into Math.max() or Math.sqrt()?

No, built-in Math methods only accept regular number values and throw a TypeError when given a BigInt.

What does typeof 42n return?

It returns "bigint", which makes checking for BigInt values straightforward with typeof value === "bigint".

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum