Abhay Jain

Jan 1, 2021

2 min read

BigInt in JavaScript

This is a recent addition to the language.

BigInt is a special numeric type that provides support for integers of arbitrary length.

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.

Math operators

BigInt can mostly be used as a regular number, for example:

alert(5n / 2n); // 2

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 BigInt() or Number(), like this:

// number to bigint
alert(bigint + BigInt(number)); // 3
// bigint to number
alert(Number(bigint) + number); // 3

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.

The unary plus is not supported on Bigints

alert( +bigint ); // error

So we should use Number() to convert a BigInt to a number.

Comparisons

Comparisons, such as <, > work with bigints and numbers just fine:

alert( 2n > 1 ); // true

Please note though, as numbers and bigints belong to different types, they can be equal ==, but not strictly equal ===:

alert( 1 === 1n ); // false

Boolean operations

When inside if or other boolean operations, bigints behave like numbers.

For instance, in if, bigint 0n is falsy, other values are truthy:

Boolean operators, such as ||, && and others also work with bigints similar to numbers:

alert( 0n || 2 ); // 2 (0n is considered falsy)