Skip to main content

Javascript BigInt

JavaScript BigInt is a new data type introduced in ES2020 (also known as ECMAScript 2020) that allows you to represent integers with arbitrary precision.

The BigInt data type is designed to address the limitations of the Number data type, which can only represent integers up to 2^53 - 1 accurately.

To create a BigInt value in JavaScript, you can add the n suffix to a numeric literal or use the BigInt() constructor:

const bigNumber1 = 123456789012345678901234567890n;
const bigNumber2 = BigInt("123456789012345678901234567890");

The BigInt data type supports standard arithmetic operations, such as addition (+), subtraction (-), multiplication (*), and division (/)

Example:

const a = 123456789012345678901234567890n;
const b = 987654321098765432109876543210n;
const c = a + b; // addition
const d = a - b; // subtraction
const e = a * b; // multiplication
const f = a / b; // division

BigInt cannot be mixed with other numeric types. For example, the following code will throw a TypeError:

const a = 123456789012345678901234567890n;
const b = 42;
const c = a + b; // TypeError: Cannot mix BigInt and other types, use explicit conversions

To convert a BigInt value to a Number value, you can use the Number() function or the unary + operator:

const a = 123456789012345678901234567890n;
const b = Number(a);
const c = +a;
info

Converting a BigInt value to a Number value can result in loss of precision if the BigInt value exceeds the maximum safe integer value (Number.MAX_SAFE_INTEGER), which is 2^53 - 1.