Sub topic 17
BigInt: Integers Beyond the Safe Range
This chapter assumes you already know the safe integer range covered earlier: Number.MAX_SAFE_INTEGER is 2 ** 53 - 1, and integers above it can no longer be told apart reliably. It also assumes you know the arithmetic operators, typeof, and strict equality. Here you will learn how BigInt fixes the precision problem, which operations it supports, and where it breaks code that was written for Number.
What BigInt Is
BigInt is a separate primitive type for integers of any size. A BigInt has no fixed width. It grows as large as memory allows, and it never rounds. The trade-off is that a BigInt can only hold whole numbers, so it has no fractions, no NaN, no Infinity, and no -0.
const maxSafe = Number.MAX_SAFE_INTEGER;
console.log(maxSafe + 2); // 9007199254740992 (wrong: lost precision)
console.log(BigInt(maxSafe) + 2n); // 9007199254740993n (exact)
const big = 2n ** 64n;
console.log(big); // 18446744073709551616n
console.log(typeof big); // "bigint"Creating BigInt Values
You can create a BigInt in two ways. You can append n to an integer literal, or you can call the BigInt() function. BigInt is a function and cannot be used as a constructor, so new BigInt(1) throws a TypeError.
console.log(123n); // 123n
console.log(0xffn); // 255n (hex, octal, and binary literals accept n)
console.log(1_000_000n); // 1000000n (separators work too)
console.log(BigInt(42)); // 42n
console.log(BigInt("9007199254740993")); // 9007199254740993n
console.log(BigInt("0x1f")); // 31n
console.log(BigInt(true)); // 1n
try { BigInt(1.5); } catch (e) { console.log(e.name); } // RangeError
try { BigInt("1.5"); } catch (e) { console.log(e.name); } // SyntaxError
try { BigInt("12px"); } catch (e) { console.log(e.name); } // SyntaxErrorBigInt() behaves very differently from Number() and parseInt. It returns no NaN and accepts no partial prefix: input that is not an exact integer throws an error. Wrap untrusted input in try/catch.
Arithmetic Rules
BigInt supports +, -, *, /, %, and **. Most of these behave as you would expect. A few differ from Number.
console.log(10n / 3n); // 3n (division truncates toward zero)
console.log(-7n / 2n); // -3n (not -4n)
console.log(-7n % 2n); // -1n (sign follows the dividend, like Number)
console.log(-5n); // -5n (unary minus works)
try { 1n / 0n; } catch (e) { console.log(e.name); } // RangeError (no Infinity)
try { 2n ** -1n; } catch (e) { console.log(e.name); } // RangeError (would be a fraction)
try { +1n; } catch (e) { console.log(e.name); } // TypeError (unary plus is banned)Unary plus throws because a lot of existing code uses +x to mean "give me a Number". If +x returned a BigInt, that code would quietly get the wrong type, so the language throws instead.
No implicit mixing
Arithmetic that mixes BigInt and Number throws a TypeError. JavaScript refuses to guess which type you want, because either guess could lose information: a fraction cannot fit in a BigInt, and a large BigInt cannot fit in a Number without rounding.
try {
console.log(1n + 1);
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(1n + BigInt(1)); // 2n
console.log(Number(1n) + 1); // 2
console.log(1n + "a"); // "1a" (string concatenation is allowed)Comparison and Equality
Comparisons between the two types are allowed, because comparing values cannot lose precision.
console.log(1n < 2); // true
console.log(2n > 1.5); // true
console.log(1n == 1); // true (loose equality compares values)
console.log(1n === 1); // false (different types)
console.log(Object.is(0n, -0n)); // true (there is no negative zero)
if (0n) { console.log("never"); } else { console.log("0n is falsy"); }Sorting gotcha
Array.prototype.sort converts the comparator's return value to a Number. The common comparator (a, b) => a - b returns a BigInt, so the conversion throws. Return a Number explicitly instead.
const ids = [10n, 2n, 33n];
console.log([...ids].sort()); // [10n, 2n, 33n] (default sort compares strings)
try {
[...ids].sort((a, b) => a - b);
} catch (e) {
console.log(e.name); // TypeError
}
console.log([...ids].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))); // [2n, 10n, 33n]Where BigInt Does Not Work
Many built-in APIs were designed for Number and reject BigInt.
| Operation | Result with BigInt | Workaround |
|---|---|---|
| `Math.max(1n, 2n)`, `Math.sqrt(4n)` | `TypeError` | Write the logic with comparisons and operators |
| `JSON.stringify({ id: 1n })` | `TypeError` | Convert to a string first, or use a replacer |
| `+x` | `TypeError` | Use `Number(x)` |
| `x >>> 1n` | `TypeError` | Use `>>` or `BigInt.asUintN` |
| `Number.isInteger(5n)` | `false` | Check `typeof x === "bigint"` |
| `1n + 1` | `TypeError` | Convert one side explicitly |
JSON needs particular care, because many APIs return 64-bit IDs. Serialize a BigInt as a string and parse it back on the other side:
const order = { id: 2n ** 63n - 1n, qty: 3 };
const json = JSON.stringify(order, (key, value) =>
typeof value === "bigint" ? value.toString() : value
);
console.log(json); // {"id":"9223372036854775807","qty":3}
const parsed = JSON.parse(json, (key, value) =>
key === "id" ? BigInt(value) : value
);
console.log(parsed.id); // 9223372036854775807nConverting Back to Number
Number(big) always succeeds. It rounds silently when the value is outside the safe range, so check the value before you convert.
function toSafeNumber(big) {
const n = Number(big);
if (!Number.isSafeInteger(n)) {
throw new RangeError(`${big} cannot be represented exactly as a Number`);
}
return n;
}
console.log(toSafeNumber(42n)); // 42
console.log(Number(2n ** 64n)); // 18446744073709552000 (rounded)
try { toSafeNumber(2n ** 64n); } catch (e) { console.log(e.message); }Converting to a string loses nothing, and it supports a radix and locale formatting:
console.log((255n).toString(16)); // "ff"
console.log((1234567890123456789n).toLocaleString("en-US")); // "1,234,567,890,123,456,789"Fixed-Width Wrapping
A BigInt never overflows. Some algorithms expect fixed-width integer behavior, such as hashing or emulating 64-bit integers from another language. For those cases, BigInt.asIntN(bits, x) wraps a value to a signed width and BigInt.asUintN(bits, x) wraps it to an unsigned width.
const max64 = 2n ** 63n - 1n;
console.log(BigInt.asIntN(64, max64 + 1n)); // -9223372036854775808n
console.log(BigInt.asUintN(64, -1n)); // 18446744073709551615n
console.log(BigInt.asUintN(8, 257n)); // 1nBitwise operators &, |, ^, ~, <<, and >> work on BigInt without the 32-bit truncation that applies to Number. They act as if the value were in two's complement with infinitely many sign bits.
Choosing Between Number and BigInt
Use BigInt for database IDs and timestamps in nanoseconds, such as process.hrtime.bigint() in Node.js. It also fits cryptographic arithmetic, exact factorials and combinatorics, and any integer that comes from a system using 64-bit integers. Keep Number for measurements, money in floating-point form (or in integer cents within the safe range), and anything that goes through Math. BigInt arithmetic is also slower than Number arithmetic, because engines cannot use plain machine registers for values of unlimited size.
function factorial(n) {
let result = 1n;
for (let i = 2n; i <= n; i++) result *= i;
return result;
}
console.log(factorial(25n)); // 15511210043330985984000000n
console.log(Number.isSafeInteger(Number(factorial(25n)))); // falseExercises
Exercise
What does each line print or throw? (a) 7n / -2n (b) 5n == 5 (c) Math.max(3n, 4n) (d) BigInt("0b101")
Show answer
(a) -3n, because BigInt division truncates toward zero. (b) true, because loose equality compares the values across types. (c) Throws a TypeError, because Math functions convert their arguments to Number and that conversion rejects BigInt. (d) 5n, because BigInt() accepts the 0b, 0o, and 0x prefixes in strings.
Exercise
An API returns {"userId": 12345678901234567890} as raw JSON text. Why does JSON.parse give the wrong ID, and how can you get the exact value?
Show answer
JSON.parse reads every number as a Number, so 12345678901234567890 is rounded to 12345678901234567000 before your code sees it. A reviver function cannot fix this in older engines, because it only receives the already-rounded value. The reliable fix is to have the API send the ID as a string ("12345678901234567890") and then call BigInt() on it. Newer engines also pass the original source text to a reviver as context.source, which you can hand to BigInt().
Exercise
Write a function sumIds(ids) that takes an array of BigInt values and returns their total as a BigInt, and returns 0n for an empty array.
Show answer
function sumIds(ids) { return ids.reduce((total, id) => total + id, 0n); } The initial value must be 0n, not 0. Starting from the Number 0 would make the first addition mix types and throw a TypeError.