BigInt is a built-in object that provides a way to store numbers larger than Number.MAX_SAFE_INTEGER
.
Take a look at the example below to see why BigInt is needed.
var maxIntNum = 9007199254740991;
var largeNumber = maxIntNum + 2; // 9007199254740992
The expected result for the above operation is 9007199254740993
, but we get 9007199254740992
. The reason is that JavaScript uses 64-bits to store a number, so once we try to create a number larger than this, it can’t be stored.
To solve this problem, we can use a BigInt.
We can create a BigInt in two ways:
n
to the end of the number.// add n to end of the number to create a BigIntvar num = 100000000000000000n;num + 10n; // 100000000000000010n// creating BigInt from hexadecimal literal - append n at the endvar num = 0x1fffffffffffffnnum; // 9007199254740991n// using BigInt constuctorvar num = BigInt(100000000000000000);num+10n; //100000000000000010nvar fromHex = BigInt('0x1fffffffffffff');fromHex; // 9007199254740991n
typeof
will return bigint
for BigInt numbers.
var num = 100000000000000000n;typeof num; // bigintvar num2 = BigInt(100000000000000000);typeof num2; // bigint
We can create an object from a BigInt value, the type of which will be object
.
var bigIntAsObject = Object(1n);bigIntAsObject; // BigInt {1n}typeof bigIntAsObject; // "object"
Remember, we cannot mix normal numbers with BigInts. If we try to, it will result in an error.
num + 10;
// Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
To solve this, we can convert our normal number to a BigInt with the following.
num + BigInt(10);
Arithmetic operation on BigInt is mostly like arithmetic operation on regular numbers. However, when we perform division, the fractional part in the result is removed.
var num = BigInt(10);// Additionnum + 10n; // 20n// Subtractionnum - BigInt(5); // 15n// Multiplicationnum * 10n; // 150n// Exponent operatornum ** 10n; // 10000000000n// DIVISION// when we perform division , the fractional part in the result is removedvar n = 5n;n / 2n; // 2n// MODULOvar n = 5n;n % 2n; // 1n
When BigInt is compared with non-BigInt numbers, will perform type conversion and check, using ==
but strict-equality ===
type conversion is not performed and returns false
if values and types are not matched.
10n == 10; // true
10n === 10; // false
These are similar to numerical comparisons.
1n < 2n // true2n > 1n // true2 > 2n // false2n > 2n // false2n >= 2n // true
BigInts behave like numbers when converting to booleans or checking for true
or false
values.
Boolean(0n) // false
Boolean(12n) // true
!0n; // true
!12n; // false.
The toString
method will return a string representing the specified BigInt object without n
at the end of the number.
var a = 10n;
a.toString(); //10