JavaScript BigInt: Arbitrary-Precision Integers, Operators and Pitfalls
When numbers run out of exact integers, BigInt takes over: literals and the BigInt() function, which operators work, why mixing BigInt and number throws, division that truncates, comparisons, conversions, JSON serialization, 64-bit typed arrays and when not to use BigInt.
kvi5hnuCode Sprout team member6 min readOn this page
A JavaScript number stores integers exactly only up to 2^53 - 1, about 9 quadrillion (article 11). That sounds huge, but it's not enough for 64-bit database IDs, nanosecond timestamps, cryptocurrency amounts in their smallest units, or the factorial of 25. For those, JavaScript has a second numeric type: bigint (ES2020), which holds integers of any size, exactly.

Creating BigInts
Add an n suffix to an integer literal, or call BigInt():
const big = 9007199254740993n; // too big for an exact number
console.log(big, typeof big);
console.log(0xffn, 0b1010n, 0o17n, 1_000_000n); // all integer literal forms work
console.log(BigInt(42)); // from a number (must be an integer)
console.log(BigInt("123456789012345678901234567890")); // from a string: any size
console.log(BigInt("0x1f"), BigInt(" 7 "), BigInt(true));
console.log(2n ** 64n); // 2^64, exactly
9007199254740993n bigint
255n 10n 15n 1000000n
42n
123456789012345678901234567890n
31n 7n 1n
18446744073709551616n
When converting, a few rules apply:
BigInt(1.5)throws aRangeError: a number with a fraction can't become an integer silently.BigInt("1.5")andBigInt("12abc")throw aSyntaxError. Strings must be integers, optionally with a0x,0oor0bprefix and surrounding whitespace. Note thatBigInt("")is0n.BigInt()is a function, not a constructor:new BigInt(1)is aTypeError.- Converting a number that's already beyond 2^53 gives you its already rounded value.
BigInt(9007199254740993)is9007199254740992n, because the number literal lost the last digit beforeBigIntever saw it. Create big values from strings ornliterals, never from large number literals.
Arithmetic
The usual operators work, with BigInts on both sides:
console.log(2n ** 100n);
console.log(7n + 3n, 7n - 3n, 7n * 3n);
console.log(7n / 2n, -7n / 2n); // division truncates toward zero
console.log(7n % 2n, -7n % 2n); // the remainder takes the sign of the left side
console.log(5n & 3n, 5n | 3n, ~5n, 1n << 70n); // bitwise works, on unlimited width
let factorial = 1n;
for (let i = 1n; i <= 25n; i++) factorial *= i;
console.log("25! =", factorial);
1267650600228229401496703205376n
10n 4n 21n
3n -3n
1n -1n
1n 7n -6n 1180591620717411303424n
25! = 15511210043330985984000000n
Things that don't work:
const attempts = {
"mixing types: 1n + 1": () => 1n + 1,
"unary plus: +1n": () => +1n,
"Math functions: Math.sqrt(4n)": () => Math.sqrt(4n),
"unsigned shift: 8n >>> 1n": () => 8n >>> 1n,
"division by zero: 1n / 0n": () => 1n / 0n,
"negative exponent: 2n ** -1n": () => 2n ** -1n,
};
for (const [label, attempt] of Object.entries(attempts)) {
try {
attempt();
} catch (err) {
console.log(label.padEnd(31), err.name);
}
}
mixing types: 1n + 1 TypeError
unary plus: +1n TypeError
Math functions: Math.sqrt(4n) TypeError
unsigned shift: 8n >>> 1n TypeError
division by zero: 1n / 0n RangeError
negative exponent: 2n ** -1n RangeError
Why can't I mix BigInt and number?
Neither type contains the other. A bigint can hold 2n ** 100n exactly, which number can't; a number can hold 0.5 and Infinity, which bigint can't. If 1n + 0.5 were allowed, there'd be no type that could represent every result correctly, and JavaScript would have to lose information silently. So it refuses, and you convert explicitly, choosing which way to lose information:
const count = 10n, ratio = 0.5;
console.log(Number(count) * ratio); // convert to number: fine for small values
console.log(count * BigInt(2)); // convert to bigint: only for integers
const huge = 2n ** 64n;
console.log(Number(huge)); // precision is lost when it's big
console.log(Number.isSafeInteger(Number(huge)));
5
20n
18446744073709552000
false
Before converting a bigint to a number, check that it's within the safe range: n >= BigInt(Number.MIN_SAFE_INTEGER) && n <= BigInt(Number.MAX_SAFE_INTEGER).
Comparisons and truthiness
Comparisons between bigints and numbers are allowed, because a comparison can always be answered exactly:
console.log(1n < 2, 2n > 1.5);
console.log(0n == 0, 1n == "1"); // loose equality compares the values
console.log(0n === 0); // strict equality also requires the same type
console.log(Boolean(0n), Boolean(5n)); // 0n is falsy, like 0
const mixed = [3n, 1, 2n, -1];
mixed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
console.log(mixed);
true true
true true
false
false true
[ -1, 1, 2n, 3n ]
The sort uses < and > instead of the usual (a, b) => a - b, because subtraction would mix types (and b - a on two bigints returns a bigint, which sort rejects).
Strings and JSON
String(5n) is "5", and template literals print bigints without the n. toString(radix) works too: (255n).toString(2) is "11111111". Note that console.log shows the n suffix; String doesn't.
JSON doesn't support bigint. JSON.stringify({ id: 1n }) throws a TypeError. The usual solution is to send big integers as strings, since 64-bit IDs would lose precision as JSON numbers anyway:
const order = { id: 9007199254740993n, total: 4999 };
const json = JSON.stringify(order, (key, value) =>
typeof value === "bigint" ? value.toString() : value);
console.log(json);
const parsed = JSON.parse(json, (key, value) => (key === "id" ? BigInt(value) : value));
console.log(parsed.id, typeof parsed.id);
{"id":"9007199254740993","total":4999}
9007199254740993n bigint
What if an API sends a big integer as a JSON number, like {"id": 9007199254740993}? A normal JSON.parse rounds it before your reviver runs. ES2026 fixed this: the reviver now receives a third argument, context, whose source property holds the original text, so you can write (key, value, context) => key === "id" ? BigInt(context.source) : value. The JSON article in part 11 covers this in detail.
Fixed-width 64-bit integers
Sometimes you need integers that wrap around like int64 or uint64 in other languages, for example when working with binary file formats or hashing. Two tools help:
BigInt.asIntN(bits, n)andBigInt.asUintN(bits, n)wrap a bigint to a signed or unsigned integer of that many bits:BigInt.asUintN(8, 257n)is1n, andBigInt.asIntN(8, 255n)is-1n.BigInt64ArrayandBigUint64Arrayare typed arrays of 64-bit integers (part 11), andDataViewhasgetBigInt64/setBigInt64. Node'sprocess.hrtime.bigint()returns a nanosecond timer as a bigint.
When to use BigInt (and when not)
| Use bigint for | Keep using number for |
|---|---|
| IDs and values from 64-bit systems (databases, Twitter/X-style IDs) | counters, indexes, lengths, loop variables |
| exact integer math beyond 2^53 (factorials, combinatorics) | anything with fractions |
| nanosecond timestamps | normal millisecond timestamps (Date.now()) |
| arbitrary-precision money in minor units | money in cents within the safe range |
BigInt operations are generally slower than number operations, and they can't be used with Math, array indexes expect numbers, and most library APIs expect numbers. Don't switch to bigint "to be safe"; use it where values can actually exceed 2^53. And it isn't meant for cryptography: its operations aren't constant-time, so use the Web Crypto API for that.
Common questions
Is typeof 10n "number"?
No, it's "bigint". BigInt is a separate primitive type, the seventh one.
How do I get the square root of a bigint?
Math doesn't accept bigints. For small values, BigInt(Math.floor(Math.sqrt(Number(n)))). For exact results on huge values, implement integer square root with Newton's method using bigint arithmetic, or use a library.
Why does 5n / 2n give 2n?
Bigints are integers, so division discards the fractional part, truncating toward zero: -5n / 2n is -2n. To round instead, adjust before dividing, for example (a + b / 2n) / b for positive values.
Can a bigint be negative?
Yes: -5n. The unary minus works (only unary + is forbidden, because +x is defined as "convert to number", which would lose precision).
Summary
bigintholds integers of any size exactly. Write123nor callBigInt(value); create huge values from strings or literals, not from imprecise numbers.+ - * / % **and the bitwise operators work between bigints; division truncates toward zero. Unary+,>>>andMathfunctions don't work.- Mixing bigint and number in arithmetic throws a
TypeError; convert explicitly withNumber()orBigInt(). - Comparisons and
==across the two types work;0nis falsy. JSON.stringifythrows on bigint: convert to strings. ES2026's revivercontext.sourcelets you parse big JSON numbers exactly.- Use bigint only where values can exceed 2^53; it's slower and doesn't work with
Mathor indexes.
Practice Questions
What is 7n / -2n?
Answer
-3n. The true quotient is -3.5, and bigint division truncates toward zero.
BigInt(12345678901234567890) returns 12345678901234567168n. Why, and how do you fix it?
Answer
The number literal 12345678901234567890 is beyond 2^53, so it was rounded to the nearest double before BigInt received it. Write 12345678901234567890n or BigInt("12345678901234567890").
Does 1n == 1 return true? What about 1n === 1?
Answer
true and false. Loose equality compares the mathematical values; strict equality also requires the same type.
Write a function that averages an array of bigints, returning a number.
Answer
const avg = xs => Number(xs.reduce((s, x) => s + x, 0n)) / xs.length;
Sum exactly as a bigint (starting from 0n, not 0), then convert once and divide as numbers so the result can have a fraction.
Why is +5n a TypeError but -5n fine?
Answer
Unary + means "convert to a number", which could silently lose precision for big values, so it was made an error. Unary - simply negates a bigint and keeps it a bigint.
Previous: Why 0.1 + 0.2 !== 0.3 in JavaScript: Floating-Point Precision, Rounding and Money
Next: JavaScript Strings: Literals, Escape Sequences and UTF-16 Code Units

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.