Home ยป JavaScript BigInt: A Complete Tutorial

JavaScript BigInt: A Complete Tutorial

JavaScript's BigInt is a built-in object that provides a way to represent whole numbers larger than the maximum safe integer limit (Number.MAX_SAFE_INTEGER, which is 253 – 1). While regular numbers in JavaScript (the Number type) are represented as 64-bit floating-point values, BigInt allows you to work with arbitrarily large integers.

This tutorial will introduce you to BigInt, show you how to create and use it, and highlight some of its unique characteristics.

1. What is BigInt?

BigInt is a special numeric type in JavaScript that can represent integers of arbitrary precision. It is particularly useful when dealing with very large numbers that exceed JavaScript's maximum safe integer (Number.MAX_SAFE_INTEGER).

2. Creating a BigInt

You can create a BigInt in two ways:

By appending an n to the end of an integer literal.
By using the BigInt() function.

Example 1: Creating a BigInt

// Using the `n` suffix
const bigIntLiteral = 1234567890123456789012345678901234567890n;

// Using the `BigInt` constructor
const bigIntConstructor = BigInt('1234567890123456789012345678901234567890');

console.log(bigIntLiteral); // Output: 1234567890123456789012345678901234567890n
console.log(bigIntConstructor); // Output: 1234567890123456789012345678901234567890n

Explanation: The n suffix in the first example directly creates a BigInt. The BigInt() constructor in the second example converts a string to a BigInt.

3. Basic Arithmetic with BigInt

BigInt supports basic arithmetic operations such as addition, subtraction, multiplication, division, and exponentiation. However, operations between BigInt and regular numbers (of type Number) are not allowed; both operands must be of the same type.

Example 2: Arithmetic with BigInt

const bigInt1 = 12345678901234567890n;
const bigInt2 = 98765432109876543210n;

const sum = bigInt1 + bigInt2; // Addition
const difference = bigInt2 - bigInt1; // Subtraction
const product = bigInt1 * bigInt2; // Multiplication
const quotient = bigInt2 / bigInt1; // Division
const remainder = bigInt2 % bigInt1; // Modulus

console.log(sum); // Output: 111111111011111111100n
console.log(difference); // Output: 86419753208641975320n
console.log(product); // Output: 1219326311370217952237463801111263526900n
console.log(quotient); // Output: 8n
console.log(remainder); // Output: 6172839510864197530n

Explanation: The results of arithmetic operations with BigInt are also BigInt. Notice that division using / results in the nearest whole number, truncating any decimal.

Example 3: Mixing BigInt and Regular Numbers

const bigInt = 10n;
const number = 5;

try {
  console.log(bigInt + number); // This will throw an error
} catch (error) {
  console.error(error); // Output: TypeError: Cannot mix BigInt and other types
}

// Convert `number` to `BigInt` before performing operations
const sum = bigInt + BigInt(number);
console.log(sum); // Output: 15n

Explanation: You cannot mix BigInt and regular numbers in arithmetic operations. To perform operations, you need to explicitly convert the Number to a BigInt using BigInt().

4. Comparison Operations with BigInt

Comparison operations like >, <, >=, <=, ==, and === work between BigInt and Number, but they must be used with caution.

Example 4: Comparing BigInt and Numbers

const bigInt = 10n;
const number = 10;

console.log(bigInt > 5); // Output: true
console.log(bigInt === 10n); // Output: true
console.log(bigInt === number); // Output: false (strict equality checks type)
console.log(bigInt == number); // Output: true (loose equality converts types)

Explanation: === checks both value and type, so 10n === 10 returns false. The == operator performs type conversion, so 10n == 10 returns true.

5. Type Conversion with BigInt

You can convert a BigInt to a regular Number using Number() and vice versa using BigInt().

Example 5: Converting Between BigInt and Number

const bigInt = 12345678901234567890n;
const number = Number(bigInt);

console.log(number); // Output: 1.2345678901234568e+19

const bigIntFromNumber = BigInt(12345);
console.log(bigIntFromNumber); // Output: 12345n

Explanation: Converting a large BigInt to a Number can lead to a loss of precision because Number can only safely represent integers up to 2^53 – 1.

6. Handling BigInt with Math Methods

The Math object methods (e.g., Math.pow(), Math.sqrt()) do not support BigInt. To perform such operations on large numbers, you need to implement your own logic or use libraries like bigint-math.

Example 6: Using BigInt for Exponentiation

You can use the ** operator for exponentiation with BigInt.

const base = 2n;
const exponent = 100n;

const power = base ** exponent;
console.log(power); // Output: 1267650600228229401496703205376n

Explanation: The ** operator works with BigInt for exponentiation.

7. Limitations of BigInt

No Decimals: BigInt is for whole numbers only; it does not support fractional values.

const invalidBigInt = 3.14n; // SyntaxError: Invalid or unexpected token

Cannot Use with Built-In Math Functions: Math functions like Math.sqrt() do not work with BigInt.

const bigInt = 16n;

try {
  console.log(Math.sqrt(bigInt)); // Throws a TypeError
} catch (error) {
  console.error(error); // Output: TypeError: Cannot convert a BigInt value to a number
}

Limited Compatibility: You need to be careful when using BigInt in conjunction with other libraries or functions that expect a Number.

8. Practical Example: Large Integer Calculations

Example 7: Factorial Calculation with BigInt

function factorial(n) {
  let result = 1n; // Initialize as BigInt

  for (let i = 1n; i <= n; i++) {
    result *= i;
  }

  return result;
}

const num = 20n;
console.log(`Factorial of ${num} is:`, factorial(num)); // Output: Factorial of 20 is: 2432902008176640000n

Explanation: This example calculates the factorial of a large number using BigInt. Using BigInt allows the computation of very large integers without losing precision.

Conclusion

BigInt is a powerful tool for working with large integers in JavaScript, allowing computations that would otherwise exceed the limits of the Number type.

While it has some limitations, such as incompatibility with fractional numbers and built-in math functions, BigInt provides a simple way to handle large integer calculations accurately.

By understanding how to use BigInt effectively, you can perform a wide range of numerical operations safely without worrying about integer overflow.

Feel free to explore these examples and use BigInt when dealing with large numbers in your JavaScript applications!

You may also like