Open In App

JavaScript BigInt

BigInt is a built-in object in JavaScript that provides a way to represent whole numbers larger than 2^53 - 1. The largest number that JavaScript can reliably represent with the Number primitive is 2^53 - 1, which is represented by the MAX_SAFE_INTEGER constant. BigInts are utilized in scenarios where operations on large numbers are necessary due to their ability to represent integers with arbitrary precision.

Syntax:

BigInt( number ) 
or
Appending n to end of an integer literal

JavaScript BigInt Examples

1. Creating BigInt using BigInt() Function

Example: This example creates a BigInt using the BigInt() function.

// Parameter in decimal format
let bigNum = BigInt(
  "123422222222222222222222222222222222222");
console.log(bigNum);

// Parameter in hexadecimal format
let bigHex = BigInt("0x1ffffffeeeeeeeeef");
console.log(bigHex);

// Parameter in binary format
let bigBin = BigInt(
  "0b1010101001010101001111111111111111");
console.log(bigBin);

Output
123422222222222222222222222222222222222n
36893488074118328047n
11430854655n

2. Creating BigInt by appending n

Example: This example creating a BigInt by appending n at the end of the number.

// Decimal format
let bigNum = 123422222222222222222222222222222222222n
console.log(bigNum)

// Hexadecimal format
let bigHex = 0x1ffffffeeeeeeeeefn
console.log(bigHex)

// Binary format
let bigBin = 0b1010101001010101001111111111111111n
console.log(bigBin)

Output
123422222222222222222222222222222222222n
36893488074118328047n
11430854655n

3. Comparing BigInt other types

A BigInt is similar to a Number in some ways, however, it cannot be used with methods of the builtin Math object and cannot be mixed with instances of Number in operations.

Example: Comparing BigInt with a Number.

typeof 100n === 100        // Returns false
typeof 100n == 100 // Returns true due to coercion
typeof 100n === 'bigint' // Returns true
100n < 101 // Returns true due to coercion

Sorting: An array can hold both primitive data types and BigInts. This allows the sort() method to work when both normal Number and BigInt values are present in the array.

Example:

// Array consisting of both
// Number and BigInt
let arr = [4, 2, 5n, 2n]

// Sorting the array
arr.sort()

console.log(arr)  // [2, 2n, 4, 5n]

Output
[ 2, 2n, 4, 5n ]

Usage Recommendation

The following applications are not recommended to be used with BigInt due to its implementation:

Limitations and Considerations

Supported Browsers

The browsers supporting BigInt method are listed below:

Article Tags :