Sub topic 6
BigInt and Why It Refuses to Mix with Number
This chapter assumes you know the Number type's limits from the previous chapter, especially Number.MAX_SAFE_INTEGER. It also assumes you are comfortable running snippets in a browser console or Node.js. Here you will learn what BigInt adds, why JavaScript throws instead of quietly converting between BigInt and Number, and which operations still accept both types.
What BigInt Solves
A Number is a 64-bit IEEE 754 float. It can represent every integer exactly only up to 2^53 − 1. Above that limit, neighboring integers share the same float, so arithmetic quietly gives wrong answers. BigInt is the seventh primitive type. It holds integers of any size, limited only by memory.
const limit = Number.MAX_SAFE_INTEGER; // 9007199254740991
console.log(limit + 2); // 9007199254740992 (wrong, should end in 3)
console.log(BigInt(limit) + 2n); // 9007199254740993n (exact)
console.log(typeof 10n); // "bigint"
console.log(2n ** 100n); // 1267650600228229401496703205376nBigInt is used for database IDs from 64-bit columns, nanosecond timestamps (process.hrtime.bigint() in Node.js), cryptography, and exact integer math such as factorials.
Creating BigInt values
You can create a BigInt in two ways. You can write a literal with an n suffix, or you can call the BigInt() function. BigInt() is a plain function. Calling new BigInt() throws a TypeError.
console.log(123n); // 123n
console.log(BigInt(123)); // 123n
console.log(BigInt("9007199254740993")); // 9007199254740993n (exact from a string)
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(NaN); } catch (e) { console.log(e.name); } // "RangeError"Why Mixing Throws
Most JavaScript operators coerce mismatched operands without complaint. BigInt is the exception:
try {
1n + 1;
} catch (e) {
console.log(e.message); // "Cannot mix BigInt and other types, use explicit conversions"
}The reason is that neither type can hold every value of the other:
| Direction | What gets lost | Example |
|---|---|---|
| BigInt → Number | Precision above 2^53, and range above about 1.8e308 | `Number(2n ** 64n + 1n)` returns `18446744073709552000` |
| Number → BigInt | Fractions, `NaN`, `Infinity` | `1.5`, `NaN`, and `Infinity` have no BigInt equivalent |
An implicit rule would have to pick a direction, and either choice would sometimes corrupt data with no warning. The language designers chose to throw a TypeError so that you decide which loss is acceptable.
The specification calls the conversion step ToNumeric. It works like ToNumber, except that a BigInt passes through unchanged. Only after that step does the operator check whether the two types match.
What Works and What Throws
Arithmetic rules inside BigInt
BigInt arithmetic stays in integers. Division truncates toward zero, and % takes the sign of the left operand.
console.log(7n / 2n); // 3n
console.log(-7n / 2n); // -3n
console.log(-7n % 2n); // -1n
console.log(-5n); // -5n (unary minus is fine)
try { +5n; } catch (e) { console.log(e.message); } // "Cannot convert a BigInt value to a number"
try { 5n >>> 1n; } catch (e) { console.log(e.name); } // "TypeError"
try { 1n / 0n; } catch (e) { console.log(e.name); } // "RangeError"
try { 2n ** -1n; } catch (e) { console.log(e.name); } // "RangeError"
try { Math.max(1n, 2n); } catch (e) { console.log(e.name); } // "TypeError"Unary + throws on a BigInt on purpose. Code such as asm.js relies on +x always producing a Number. The >>> operator throws because an unsigned right shift has no meaning for an integer with unlimited width. None of the Math functions accept BigInt.
Operations that accept both types
Comparison and string conversion never lose information, so they accept mixed operands:
console.log(1n < 2); // true
console.log(2n > 1.5); // true: compared by mathematical value
console.log(1n == 1); // true
console.log(1n === 1); // false: different types
console.log(1n + "px"); // "1px": a string operand means concatenation
console.log(`${10n}`); // "10"
console.log(Boolean(0n)); // false: 0n is falsy
console.log(0n || "empty"); // "empty"
console.log(new Set([1, 1n]).size); // 2: SameValueZero checks type
console.log([3n, 1, 2n, 4].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))); // [1, 2n, 3n, 4]The relational operators compare a BigInt with a Number by mathematical value, with no rounding. So 9007199254740993n > 9007199254740992 is true, even though converting the BigInt to a Number would make the two values equal. BigInt has no negative zero, so -0n is the same value as 0n.
Converting Explicitly and Safely
Number(big) never throws. It rounds silently instead. If losing precision would be a bug, check the range first:
function bigIntToSafeNumber(big) {
const max = BigInt(Number.MAX_SAFE_INTEGER);
const min = BigInt(Number.MIN_SAFE_INTEGER);
if (big > max || big < min) {
throw new RangeError(`${big} is outside the safe integer range`);
}
return Number(big);
}
function numberToBigInt(num) {
if (!Number.isInteger(num)) {
throw new RangeError(`${num} is not an integer`);
}
return BigInt(num);
}
console.log(bigIntToSafeNumber(42n) * 1.5); // 63
console.log(numberToBigInt(10) * 3n); // 30n
console.log(BigInt(Math.trunc(7.9))); // 7n: truncate deliberatelyTo wrap a BigInt to a fixed bit width, as C integer types do, use BigInt.asIntN(bits, value) for signed values or BigInt.asUintN(bits, value) for unsigned values:
console.log(BigInt.asUintN(64, -1n)); // 18446744073709551615n
console.log(BigInt.asIntN(8, 255n)); // -1nGotcha: JSON
JSON.stringify throws on BigInt, because JSON numbers are usually parsed back into floats. Convert BigInt values to strings yourself, and convert them back when you parse:
const order = { id: 9007199254740993n, qty: 2 };
try { JSON.stringify(order); } catch (e) { console.log(e.message); }
// "Do not know how to serialize a BigInt"
const json = JSON.stringify(order, (key, value) =>
typeof value === "bigint" ? value.toString() : value
);
console.log(json); // {"id":"9007199254740993","qty":2}
const parsed = JSON.parse(json, (key, value) =>
key === "id" ? BigInt(value) : value
);
console.log(parsed.id); // 9007199254740993nChoosing Between BigInt and Number
| Situation | Use |
|---|---|
| Integers that can exceed 2^53 − 1 (64-bit IDs, nanosecond timestamps) | BigInt |
| Any value with fractions, such as money in floats, measurements, or ratios | Number, or integer cents as Number |
| Heavy numeric loops, `Math` functions, typed arrays | Number (BigInt is slower and incompatible with `Math`) |
| Exact large integer math, such as factorials or modular arithmetic | BigInt |
Keep each value in one type throughout a module, and convert only at the boundaries: input parsing, JSON, and APIs that require Number.
Exercise
Predict each result or error: (a) 10n / 3n, (b) 5n + 5, (c) 5n > 4.9, (d) "id:" + 7n, (e) BigInt(0.1 + 0.2).
Show answer
(a) 3n, because division truncates. (b) TypeError, because BigInt and Number cannot be mixed in arithmetic. (c) true, because relational operators compare by mathematical value. (d) "id:7", because a string operand makes + concatenate. (e) RangeError, because 0.30000000000000004 is not an integer.
Exercise
Why does BigInt(12345678901234567890) produce 12345678901234567168n, and how do you get the exact value?
Show answer
The number literal is parsed as a float before BigInt runs, so it is already rounded to the nearest representable double. Write BigInt("12345678901234567890") or the literal 12345678901234567890n.
Exercise
A function receives either a Number or a BigInt and must return its value doubled, in the same type. Write it without triggering a mixing error.
Show answer
function double(x) { return typeof x === "bigint" ? x 2n : x 2; }. The typeof check makes each branch use an operand of the matching type.