BigInt

There is a specific numeric type, providing support for integers of arbitrary length. It’s known as biting.

You can create a bigint by appending n to the end of an integer literal. Another way of creating a bigint is to call the function BigInt, which generates bigints from numbers, strings, and so on.

Let’s see it in action:

const bigint = 12345678901896532147759012345678901234567890n;
console.log(bigint);
const sameBigint = BigInt("12345678901896532147759012345678901234567890");
console.log(sameBigint);
const bigintFromNumber = BigInt(20); // same as 20n
console.log(bigintFromNumber);

Math Operators

Most of all BigInt is applied as a regular number, like here:

console.log(1n + 3n); // 4
console.log(7n / 2n); // 3

The 7/2 division will return the result rounded towards zero. All the actions with bigints return only bigints.

Also, regular numbers and bigints can be mixed, like this:

console.log(1n + 2); // Error: Cannot mix BigInt and other types

If it is required, you can convert them using either Number() or BigInt() as follows:

let bigint = 1n;
let number = 3;
// number to bigint
console.log(bigint + BigInt(number)); // 4
// bigint to number
console.log(Number(bigint) + number); // 4

You should be careful with such operations. Although conversions are silent and don’t cause errors, once the bigint is too large and doesn’t fit the number type, then additional bits will be cut off.

As you know, the unary plus operator +value is widely used for converting the value to a number. But, it is not supported on bigints.

Comparisons

Comparisons (<,>) operate with numbers and bigints properly.

Here is an example:

console.log(3n > 1n); // true
console.log(3n > 1); // true

Due to the fact that numbers and bigints are of different types, they may be equal == but not strictly equal ===. Here is an example:

console.log(1 == 1n); // true
console.log(1 === 1n); // false

Boolean Operations

Bigints behave like numbers inside if and other boolean operations. For example, inside if, 0n is will bring false, and other values -true:

if (0n) {
  // never executed
}

Boolean operations (||, &&) work with bigints like numbers, as follows:

console.log(1n || 2); // 1 (1n is truthy)
console.log(0n || 2); // 2 (0n is  falsy)

Polyfills

It can be tricky to polyfill bigints. That’s because most of the JavaScript operators behave differently with bigints compared to regular numbers. Bigints always return bigints. To emulate behavior like that, polyfill is required. It is necessary for analyzing the code and replacing all such operators with the functions.

The developers of the JSBI library use big numbers in their methods. They can be used instead of bigints. Their approach suggests writing the code in JSBI rather than native bigints. It works with numbers like with bigints internally. So, the code will be bigint-read.




Do you find this helpful?

Related articles