HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript BigInt

JavaScript BigInt is a special numeric data type that can represent integers with arbitrary precision. It was introduced in ES2020 to solve the problem of accurately representing very large numbers that are outside the range of the standard Number type.


The Problem with Large Numbers

JavaScript numbers are 64-bit floating-point values. This means they have a limit to how large an integer can be while remaining accurate. This limit is known as the Safe Integer limit:

  • Number.MAX_SAFE_INTEGER = 9,007,199,254,740,991
  • Number.MIN_SAFE_INTEGER = -9,007,199,254,740,991

If you try to perform math on integers larger than this using the standard Number type, you will get inaccurate results.


How to Create a BigInt

You can create a BigInt by either adding an n to the end of an integer or by using the BigInt() function.

let big1 = 9007199254740995n;
let big2 = BigInt("9007199254740995");

console.log(typeof big1); // "bigint"

BigInt Operations

You can use most standard arithmetic operators with BigInt, such as +, -, *, **, and %. However, unsigned right shift (>>>) cannot be used on a BigInt.

Important Rule: No Mixing

You cannot perform operations between a BigInt and a standard Number. You must convert one of them to the same type as the other.

let x = 5n;
let y = 10;

// let result = x + y; // Error! Cannot mix BigInt and other types

let result = x + BigInt(y); // Works correctly
Warning: When performing division on BigInt, the result is always an integer. Anything after the decimal point is rounded towards zero.

Precision of BigInt

BigInt allows you to handle massive numbers accurately, which is essential in cryptography, scientific calculations, and financial applications dealing with microscopic values (like Satoshi in Bitcoin).

let hugeNumber = 123456789012345678901234567890n;
let total = hugeNumber + 1n;
console.log(total.toString()); // Accurate to the last digit!

Key Points to Remember

  • BigInt was introduced in ES2020 to handle very large integers
  • Create it by adding n (e.g., 100n) or using BigInt()
  • The standard Number type loses precision above ~9 quadrillion
  • You cannot mix BigInt with standard numbers in calculations
  • Division with BigInt always truncates the decimal part