Skip to content

JavaScript BigInt

  • by

JavaScript BigInt allows you to represent whole numbers larger 253 - 1. The bigint is the primitive type like number, string, symbol, boolean undefined, and null.

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

A BigInt is created by appending n to the end of an integer literal or by calling the function BigInt that creates BigInt from strings, numbers, etc.

JavaScript BigInt

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
  // Parameter in decimal format
  var bigNum = BigInt("123422222222222222222222222222222222222");
  console.log(bigNum);

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

  // Parameter in binary format
  var bigBin = BigInt("0b1010101001010101001111111111111111");
  console.log(bigBin);
</script>
</body>
</html>

Output:

JavaScript BigInt

Type: The type of a BigInt is bigint. For example:

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

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

Comparisons

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

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

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 Number in these cases. For example:

let count = 0n;

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

Do comment if you have any doubts or suggestions on this JS topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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