Summary: in this tutorial, you’ll learn about the BigInt
type which is the built-in object that can represent whole numbers larger than 253 – 1.
Introduction to the JavaScript BigInt
ES2020 introduced a new built-in object called BigInt
that allows you to represent whole numbers larger 253 - 1
.
The bigint
is the primitive type like number
, string
, symbol
, boolean
undefined
, and null
.
To make a BigInt
, you append n
to the end of the number literal, for example:
Code language: JavaScript (javascript)let bigInt = 9007199254740991n;
Alternatively, you can call the function BigInt()
:
Code language: JavaScript (javascript)let bigInt = BigInt(9007199254740991);
See the following calculation with a Number
:
Code language: JavaScript (javascript)let x = Number.MAX_SAFE_INTEGER; x = x + 1; // 9007199254740992 x = x + 1; // 9007199254740992 (same as above)
and with a BigInt
:
Code language: JavaScript (javascript)let x = BigInt(Number.MAX_SAFE_INTEGER); x = x + 1; // 9007199254740992n x = x + 1; // 9007199254740993n (correct now)
Type
The type of a BigInt
is bigint
. For example:
Code language: JavaScript (javascript)console.log(typeof bigInt); // bigint console.log(typeof BigInt(100) === 'bigint'); // true
Operators
The BigInt
supports the following operator +
, *
, -
, **
, %
, bitwise operators except >>>
(zero-fill right shift). It doesn’t support the unary operator (+
).
The /
operator will also work with the whole numbers. However, the result will not return any fractional digits. For example:
Code language: JavaScript (javascript)let result = 3n / 2n; console.log(result); // 1n, not 1.5n
Comparisons
A BigInt
is not strictly equal (===
) to a Number
:
Code language: JavaScript (javascript)console.log(1n === 1); // false
However, a BigInt
is loosely equal to a number when you use the ==
operator:
Code language: JavaScript (javascript)console.log(1n == 1); // true
You can use the <
, <=
, >
, >=
to compare a BigInt
with a Number
:
Code language: JavaScript (javascript)console.log(1n < 2); // true console.log(2n > 1); // true console.log(2n >= 2); // true
Conditionals
A BigInt
is converted to a Boolean
via the Boolean()
function in conditionals such as if
statement or logical operators ||
, &&,
!
. In other words, it works like a Number
in these cases. For example:
Code language: JavaScript (javascript)let count = 0n; if(count) { console.log(true); } else { console.log(false); }
Summary
- The
BigInt
is a new primitive type that can represent whole numbers bigger than253 - 1
, which is the largest number Javascript can reliably represent with thenumber
type. - Добавьте
n
к целому числу или используйте функциюBigInt()
для созданияbigint
.