BigInt for large numbers in JavaScript
Intermediate · 3 min read
Ordinary JavaScript numbers stop being exact past about nine thousand trillion. For bigger whole numbers, such as large IDs, cryptography, or 2 to the 64th, JavaScript has a second number type: BigInt. It can hold whole numbers of any size, exactly.
In this tutorial you will compute 2 to the 64th with BigInt, then find three things a BigInt refuses to do that a normal number allows. Those refusals are deliberate, and they are what keep BigInt exact. You need to know typeof and try/catch.
Writing a BigInt
A BigInt is a whole number with an n on the end:
console.log(typeof 10n); // bigint
console.log(typeof 10); // number
You can also make one from a number or a string with BigInt(...):
console.log(String(BigInt('9007199254740993'))); // 9007199254740993
Passing a string keeps every digit. String(...) turns the result into text for printing. If you console.log a BigInt directly, it shows with its n, like 10n.
Why a second type?
Normal numbers are doubles: they store about 16 significant digits and round the rest. A BigInt stores every digit, so it uses more memory and is slower, and it can't hold fractions. It is a tool for whole numbers that must stay exact.
Here is the exercise. Try it yourself first if you like, then read on and we will build it step by step.
19 BigInt for exact large arithmetic
fairCompute 2 ** 64 exactly with BigInt. Then find three things a BigInt refuses to do that a Number allows.
Stuck? Three hints, smallest first
- 1. A
BigIntliteral ends inn, andtypeofreports‘bigint’. - 2. Mixing a
BigIntand aNumberin arithmetic throws aTypeError. - 3. There is no fractional
BigInt, so division truncates, andJSON.stringifyrefuses it outright.
Step 1: 2 to the 64th
const big = 2n ** 64n;
console.log(big.toString()); // 18446744073709551616
console.log(typeof big); // bigint
Both sides of ** are BigInts, so the answer is a BigInt too, with all 20 digits exact.
Step 2: exact past the safe limit
Compare a BigInt with a normal number just past the safe limit, 2 to the 53rd:
console.log(2n ** 53n + 1n === 9007199254740993n); // true
console.log(2 ** 53 + 1 === 2 ** 53); // true
The BigInt sum is exactly right. The normal sum can't move: adding 1 to 2 to the 53rd gives back the same number.
Step 3: refusal one, no mixing
The natural wrong turn is to add a BigInt and a normal number:
try {
console.log(1n + 1);
} catch (e) {
console.log(e.message); // Cannot mix BigInt and other types, use explicit conversions
}
This throws a TypeError. (The message is node's wording; browsers may phrase it differently.) It seems annoying at first, but it protects you: if JavaScript quietly turned the BigInt into a normal number, you could lose digits without noticing.
Convert one side yourself, so the choice is visible in your code:
console.log(String(1n + BigInt(1))); // 2
console.log(Number(1n) + 1); // 2
Comparisons are allowed across the two types. 10n == 10 is true, but 10n === 10 is false, because === also checks the type.
Step 4: refusal two, no fractions
A BigInt can only be a whole number, so division throws away the remainder:
console.log(String(7n / 2n)); // 3
console.log(String(-7n / 2n)); // -3
7n / 2n is 3, not 3.5. It cuts towards zero, so -7n / 2n is -3. If you need money in BigInt, store whole kobo, which you should be doing anyway.
Step 5: refusal three, no JSON
JSON.stringify turns data into text to send to a server. It refuses BigInts:
try {
JSON.stringify({ big: 1n });
} catch (e) {
console.log(e.name); // TypeError
}
console.log(JSON.stringify({ big: String(2n ** 64n) })); // {"big":"18446744073709551616"}
Instead of guessing, it throws. Send a BigInt as a string, and turn it back with BigInt(text) on the other side.
Step 6: Math doesn't take BigInts
One more limit worth knowing: the Math functions only work on normal numbers. Math.sqrt(4n) throws a TypeError too. For BigInts you write the math with operators like *, /, % and **.
The full solution
The answer panel computes 2 to the 64th, compares exact and rounded sums past the safe limit, and catches the errors from mixing types and from JSON.stringify. The checks underneath confirm each refusal, including that 7n / 2n is 3n. Press Run to see the output.
const big = 2n ** 64n;
const mixed = (() => {
try { return String(1n + 1); } catch (e) { return e.constructor.name; }
})();
const jsonRefused = (() => {
try { return JSON.stringify({ big: 1n }); } catch (e) { return e.constructor.name; }
})();
console.log('2n ** 64n :', big.toString());
console.log('typeof :', typeof big);
console.log('exact past 2^53:', (2n ** 53n + 1n).toString());
console.log('as a Number :', (2 ** 53) + 1, '<- did not move');
console.log('1n + 1 :', mixed);
console.log('7n / 2n :', (7n / 2n).toString(), '<- truncated, no fraction exists');
console.log('JSON.stringify :', jsonRefused);
console.log('loose vs strict:', 10n == 10, 10n === 10);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a BigInt literal ends in n', typeof 10n, 'bigint');
test('and it is exact past 2 ** 53', 2n ** 53n + 1n === 9007199254740993n, true);
test('where a double is not', (2 ** 53) + 1 === 2 ** 53, true);
test('mixing a BigInt with a Number throws', mixed, 'TypeError');
test('loose equality does cross the types', 10n == 10, true);
test('strict equality does not', 10n === 10, false);
test('division truncates, since there are no fractions', 7n / 2n === 3n, true);
test('JSON.stringify refuses a BigInt outright', jsonRefused, 'TypeError');
test('so send it as a string', String(big), '18446744073709551616');
BigInt is arbitrary-precision integers, and the deliberate friction is the point: refusing to mix with Number means you can never accidentally lose precision by adding a float. Convert explicitly with BigInt(n) or Number(b) and take responsibility at that line.
Three practical limits. Division truncates, so BigInt is no use for money with fractions unless you scale to minor units first — which you should be doing anyway. JSON.stringify throws rather than guessing, so a BigInt in an API payload needs converting to a string by hand. And Math.* functions do not accept BigInts at all: Math.sqrt(4n) throws.
Common mistakes
- Mixing
1n + 1. It throws aTypeError. Convert one side withBigInt(...)orNumber(...). - Making a big BigInt from a number.
BigInt(9007199254740993)receives an already-rounded number. Pass the digits as a string. - Expecting a fraction from division.
7n / 2nis3n. BigInt has no decimals.
Try it yourself
- Compute 30 factorial (1 times 2 times 3, all the way to 30) with BigInt and count its digits.
- Write
toJSONSafe(obj)that turns every BigInt value in a flat object into a string. - Find out what
BigInt(1.5)does, and why.