JavaScript BigInt

Created with Sketch.

JavaScript BigInt

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:

let bigInt = 9007199254740991n;

Code language: JavaScript (javascript)

Alternatively, you can call the function BigInt():

let bigInt = BigInt(9007199254740991);

Code language: JavaScript (javascript)

See the following calculation with a Number:

let x = Number.MAX_SAFE_INTEGER;
x = x + 1; // 9007199254740992
x = x + 1; // 9007199254740992 (same as above)

Code language: JavaScript (javascript)

and with a BigInt:

let x = BigInt(Number.MAX_SAFE_INTEGER);
x = x + 1; // 9007199254740992n
x = x + 1; // 9007199254740993n (correct now)

Code language: JavaScript (javascript)

Type

The type of a BigInt is bigint. For example:

console.log(typeof bigInt); // bigint
console.log(typeof BigInt(100) === 'bigint'); // true

Code language: JavaScript (javascript)

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:

let result = 3n / 2n;
console.log(result); // 1n, not 1.5n

Code language: JavaScript (javascript)

Comparisons

A BigInt is not strictly equal (===) to a Number:

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

Code language: JavaScript (javascript)

However, a BigInt is loosely equal to a number when you use the == operator:

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

Code language: JavaScript (javascript)

You can use the <, <=, >, >= to compare a BigInt with a Number:

console.log(1n < 2); // true
console.log(2n > 1); // true
console.log(2n >= 2); // true

Code language: JavaScript (javascript)

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:

let count = 0n;

if(count) {
console.log(true);
} else {
console.log(false);
}

Code language: JavaScript (javascript)

Summary

  • The BigInt is a new primitive type that can represent whole numbers bigger than 253 - 1, which is the largest number Javascript can reliably represent with the number type.
  • Append n to a literal integer or use BigInt() function to create a bigint.

Leave a Reply

Your email address will not be published. Required fields are marked *