BigInt is a special numeric type that provides support for integers of arbitrary length.
A bigint is created by appending
n to the end of an integer literal or by calling the function
BigInt that creates bigints from strings, numbers etc.
const bigint = 1234567890123456789012345678901234567890n; const sameBigint = BigInt("1234567890123456789012345678901234567890"); const bigintFromNumber = BigInt(10); // same as 10n
BigInt can mostly be used like a regular number, for example:
Please note: the division
5/2 returns the result rounded towards zero, without the decimal part. All operations on bigints return bigints.
We can’t mix bigints and regular numbers:
We should explicitly convert them if needed: using either
Number(), like this:
The conversion operations are always silent, never give errors, but if the bigint is too huge and won’t fit the number type, then extra bits will be cut off, so we should be careful doing such conversion.
Comparisons, such as
> work with bigints and numbers just fine:
Please note though, as numbers and bigints belong to different types, they can be equal
==, but not strictly equal
if or other boolean operations, bigints behave like numbers.
For instance, in
0n is falsy, other values are truthy:
Boolean operators, such as
&& and others also work with bigints similar to numbers:
- and so on behave differently with bigints compared to regular numbers.
For example, division of bigints always returns a bigint (rounded if necessary).
To emulate such behavior, a polyfill would need to analyze the code and replace all such operators with its functions. But doing so is cumbersome and would cost a lot of performance.
So, there’s no well-known good polyfill.
Although, the other way around is proposed by the developers of https://github.com/GoogleChromeLabs/jsbi library.
This library implements big numbers using its own methods. We can use them instead of native bigints:
|Creation from Number||
…And then use the polyfill (Babel plugin) to convert JSBI calls to native bigints for those browsers that support them.
In other words, this approach suggests that we write code in JSBI instead of native bigints. But JSBI works with numbers as with bigints internally, emulates them closely following the specification, so the code will be “bigint-ready”.
We can use such JSBI code “as is” for engines that don’t support bigints and for those that do support – the polyfill will convert the calls to native bigints.