BigInt in JavaScript
BigInt in JavaScript: The new standard for integers
For many years, JavaScript's limitation on integer size posed a problem when working with large numbers. However, ECMAScript 2020 introduced a new data type: BigInt, which allows working with arbitrarily large integers.
This article will discuss:
BigInt is a new primitive type in JavaScript that allows storing integers much larger than what the Number type can handle.
JavaScript's standard Number type is based on the IEEE 754 double-precision floating-point format, which supports values up to Number.MAX_SAFE_INTEGER (2⁵³ - 1, or 9007199254740991). Beyond this, inaccuracies can occur.
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MAX_SAFE_INTEGER + 1); // 9007199254740992
console.log(Number.MAX_SAFE_INTEGER + 2); // 9007199254740992 😱
Here, we see a loss of precision.
There are two primary ways to create BigInt values:
const big = 1234567890123456789012345678901234567890n;
Simply append n
to the end of an integer.
const big = BigInt("1234567890123456789012345678901234567890");
You can pass a string or a number to the function.
You can perform basic mathematical operations with BigInt:
const a = 1234567890123456789012345678901234567890n;
const b = 987654321098765432109876543210987654321n;
console.log(a + b); // addition
console.log(a - b); // subtraction
console.log(a * b); // multiplication
console.log(a / b); // division (rounds toward zero)
console.log(a % b); // remainder
Note: BigInt division always rounds toward zero, even when there's a remainder.
JavaScript does not allow mixing Number and BigInt in the same operation:
const big = 10n;
const num = 5;
console.log(big + num); // TypeError
To combine them, you must explicitly convert the types:
console.log(big + BigInt(num));
console.log(Number(big) + num);
Attempting to serialize BigInt with JSON will throw an error:
JSON.stringify({ value: 123n }); // TypeError
You must first convert it to a String or Number:
JSON.stringify({ value: String(123n) }); // "{\"value\":\"123\"}"
typeof 123n; // "bigint"
You can compare BigInt and Number (if their values match):
123n == 123; // true
123n === 123; // false (different types)
BigInt does not work with certain Web APIs and DOM manipulations (e.g., Canvas, WebGL).
Math methods cannot be used with BigInt:
Math.sqrt(25n); // TypeError
BigInt cannot have decimal values:
10.5n; // SyntaxError