BigInt
is a built-in object that provides a way to represent a whole number larger than 253 - 2, which is the largest number JavaScript can represent with Number
. BigInt
is created by appending n to the end of an integer literal or invoking the BigInt
function that creates bigints from string, number etc.
EXAMPLE!
// wasys to create BigInt
const bigint = 12345678901234567890n;
// string => BigInt
const bigint1 = BigInt("12345678901234567890");
// number => BigInt
const bigint2 = BigInt(10);
Maths operators
BigInt is mostly used like regular number, but we can't mix bigints and regular numbers. Example:
const bigint = 10n;
const bigint1 = 20n;
const number = 10;
console.log(bigint + bigint1); // 30n
console.log(bigint + number);
// typeerror: cannot mix BigInt and other types
We should explicitly convert them if needed, either using BigInnt()
or Number()
.
// number => bigint
console.log(bigint + BigInt(number));
// bigint => number
console.log(Number(bigint) + number);
Comparison: Comparisons such as <
, >
work with bigints and numbers are just fine. Number and BigInts can be equal(==) but can't be strictly equal(===).
Example:
// Greater or lesser
const bigint = 20n;
const bigint1 = 10n;
const number = 10;
console.log(bigint > bigint1); //true
console.log(bigint ? number); // true
// equals comparison
const bigint = 10n;
const number = 10;
console.log(bigint == number); // true
console.log(bigint === number); // false
Thanks for Reading👀