BigInt
is a new data type that allows you to work with integers larger than Number.MAX_SAFE_INTEGER
, which is the largest number that can be represented with the number
data type.
To create a BigInt
, you can append the letter n
to the end of an integer or use the BigInt()
constructor
const bigNumber = 1234567890123456789012345678901234567890n;
const anotherBigNumber = BigInt(1234567890123456789012345678901234567890);
BigInt
can be used with mathematical operators and functions like any other number type. However, you cannot mix BigInt
and regular number
types in the same operation
const bigNumber = 1234567890123456789012345678901234567890n;
const regularNumber = 123;
// This will result in an error
const result = bigNumber + regularNumber;
You can convert a BigInt
to a regular number
using the Number()
function, but be aware that this can cause precision loss if the BigInt
is larger than Number.MAX_SAFE_INTEGER
const bigNumber = 1234567890123456789012345678901234567890n;
const regularNumber = Number(bigNumber); // This will cause precision loss
BigInt
can also be used with some built-in functions like parseInt()
and JSON.stringify()
, but not all functions and libraries support BigInt
yet.
BigInt
is a useful addition to JavaScript that allows you to work with integers larger than Number.MAX_SAFE_INTEGER
. While it has some limitations and requires careful handling, it provides a powerful tool for working with large numbers in JavaScript.