JavaScript Reference ยท Number and BigInt
The BigInt type and BigInt() function
Reference for JavaScript BigInt: literals with n, BigInt(), arithmetic rules, mixing with numbers, comparison, division, toString() and JSON limits.
BigInt is a primitive type for whole numbers of any size. Where a normal number loses exactness beyond Number.MAX_SAFE_INTEGER (about 9 quadrillion), a BigInt stays exact until the engine runs out of memory. You write one by adding n to an integer literal, or by calling BigInt().
Use BigInt for large identifiers, exact factorials and combinatorics, cryptography-style math and 64-bit values. Do not use it for everyday counting; numbers are faster and work with the whole Math library.
const big = 9007199254740993n; big + 1n; // 9007199254740994n BigInt("123456789012345678901234567890");
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
123n // literal BigInt(value) // conversion (not with new) BigInt.asIntN(bits, big) BigInt.asUintN(bits, big)
| Name | Description |
|---|---|
value |
A number that is an integer, a string holding integer text (decimal, 0x, 0o or 0b), a boolean, or another BigInt. |
Return value: a BigInt primitive.
Exceptions: a RangeError when a number is not an integer (BigInt(1.5), BigInt(NaN)). A SyntaxError when a string cannot be parsed as an integer. A TypeError for new BigInt(), and for undefined, null or a symbol.
Usage notes
- No mixing in arithmetic.
1n + 1throws aTypeError. Convert explicitly withBigInt(n)orNumber(big). Converting to a number may lose precision. - Division truncates.
7n / 2nis3n; there are no fractional BigInts.%takes the sign of the left operand. - Operators supported:
+ - * / % **and the bitwise operators& | ^ ~ << >>. The unsigned shift>>>and unary+throw. A negative exponent in**throws aRangeError. - Comparisons:
<,>,==work with numbers, so1n == 1istrue;1n === 1isfalsebecause the types differ. Sorting mixed arrays works with a comparator such as(a, b) => (a < b ? -1 : a > b ? 1 : 0); subtracting would throw. - Truthiness:
0nis falsy, every other BigInt is truthy. - No
Mathsupport. Functions such asMath.sqrt()andMath.max()reject BigInts. - JSON:
JSON.stringify()throws on a BigInt. Convert to a string first, or giveBigInt.prototypeatoJSONmethod if you control the program. - Parsing:
parseInt()andparseFloat()return numbers. UseBigInt("...")for large integer text; it does not trim partial input. - Speed: BigInt math is slower than number math and uses more memory for huge values.
- Wrapping to a fixed width is done with
BigInt.asIntN()andasUintN().
Browser support
BigInt is supported in all current browsers and in Node.js. Very old browsers and some older tooling cannot parse the 123n literal, so check the targets of your build tool.