JavaScript BigInt is a special numeric data type that can represent integers
with arbitrary precision. It was introduced in ES2020 to solve the problem of accurately
representing very large numbers that are outside the range of the standard
Number type.
JavaScript numbers are 64-bit floating-point values. This means they have a limit to how large an integer can be while remaining accurate. This limit is known as the Safe Integer limit:
Number.MAX_SAFE_INTEGER = 9,007,199,254,740,991Number.MIN_SAFE_INTEGER = -9,007,199,254,740,991If you try to perform math on integers larger than this using the standard Number type,
you will get inaccurate results.
You can create a BigInt by either adding an n to the end of an
integer or by using the BigInt() function.
let big1 = 9007199254740995n;
let big2 = BigInt("9007199254740995");
console.log(typeof big1); // "bigint"
You can use most standard arithmetic operators with BigInt, such as
+, -, *, **, and %.
However, unsigned right shift (>>>) cannot be used on a BigInt.
You cannot perform operations between a BigInt and a standard Number.
You must convert one of them to the same type as the other.
let x = 5n;
let y = 10;
// let result = x + y; // Error! Cannot mix BigInt and other types
let result = x + BigInt(y); // Works correctly
BigInt, the result is
always an integer. Anything after the decimal point is rounded towards
zero.
BigInt allows you to handle massive numbers accurately, which is essential in cryptography, scientific calculations, and financial applications dealing with microscopic values (like Satoshi in Bitcoin).
let hugeNumber = 123456789012345678901234567890n;
let total = hugeNumber + 1n;
console.log(total.toString()); // Accurate to the last digit!
BigInt was introduced in ES2020 to handle very large
integersn (e.g., 100n) or using
BigInt()Number type loses precision above ~9 quadrillionBigInt always truncates the decimal part