BigInt

BigInt

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 big hint is to call the function BigInt, which generates begins 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 begins 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 begins.

Comparisons

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

Here is an example:

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

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

Due to the fact that numbers and bigots 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 if0n is will bring false, and other values -true:

if (0n) {
  // never executed
}

Boolean operations (||&&) work with begins 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 begins. That’s because most of the JavaScript operators behave differently with begins compared to regular numbers. Bigints always return begins. To emulate behavior like that, a 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 begins. Their approach suggests writing the code in JSBI rather than native begins. It works with numbers like which begins internally. So, the code will be bigint-read.

Reactions

Post a Comment

0 Comments

close