Back to JavaScript
2026-01-185 min read

BigInt (JavaScript)

Learn BigInt (JavaScript) step by step with clear examples and exercises.

Title: Mastering Large Integer Arithmetic with JavaScript's BigInt Data Type

Why This Matters

In this full guide, we delve into the world of large integers using JavaScript's BigInt data type. Understanding BigInt is crucial when dealing with numbers that are too large for JavaScript's native Number type or performing complex mathematical operations involving large integers. This knowledge will prove invaluable during coding interviews, real-world programming challenges, and even debugging larger projects.

Prerequisites

To fully grasp the concepts covered in this lesson, you should have a solid understanding of:

  1. Basic JavaScript syntax
  2. Variables and data types
  3. Arithmetic operations (addition, subtraction, multiplication, division)
  4. Control structures (if-else statements, loops)
  5. Understanding the limitations of JavaScript's Number primitive when dealing with large integers
  6. Familiarity with common mathematical concepts such as factors, multiples, prime numbers, and Fibonacci sequences
  7. Knowledge of recursion and iterative approaches to solving problems

Core Concept

BigInt represents integer values that are too high or too low to be represented by the Number primitive in JavaScript. You can create a BigInt value by appending n to the end of an integer literal, or by calling the BigInt() function and giving it an integer value or string value.

Here's how to create a BigInt:

const hugeNumber = 9007199254740991n; // Using the n suffix
const anotherHugeNumber = BigInt(9007199254740991); // Using the BigInt() function

You can perform arithmetic operations on BigInt values just like regular numbers:

const a = 3n;
const b = 5n;
const sum = a + b;
console.log(sum); // Outputs: 8n

Comparing and converting BigInt values

To compare two BigInt values, use the >, <, or == operators:

const a = 5n;
const b = 7n;
console.log(a < b); // Outputs: true

You can convert a BigInt to a string using the toString() method:

const bigNumber = 9007199254740991n;
console.log(bigNumber.toString()); // Outputs: "9007199254740991"

Common BigInt methods

The BigInt() constructor has a static method called BigInt.asIntN(), which converts a string to an integer and truncates any digits beyond the specified number of base-10 digits:

const bigString = "90071992547409910";
console.log(BigInt.asIntN(bigString, 19)); // Outputs: 9007199254740991n

Additionally, BigInt provides the BigInt.prototype.abs() method to get the absolute value of a BigInt and the BigInt.prototype.sqrt() method for finding the square root (though Note that that the square root function may not always return an exact result).

BigInt with other data types

When performing arithmetic operations involving BigInt and other data types, JavaScript will automatically convert the other data type to a BigInt if necessary. However, be mindful of potential issues when mixing BigInts with floating-point numbers (as BigInt only supports integer operations).

Worked Example

Let's work through an example that involves calculating the factorial of a large number using BigInt.

function factorial(n) {
if (n === 0n || n === 1n) return 1n;
let result = 1n;
for (let i = 2n; i <= n; i++) {
result *= i;
}
return result;
}

const hugeFactorial = factorial(100n);
console.log(hugeFactorial); // Outputs the factorial of 100 as a BigInt

Common Mistakes

  1. Forgetting to append 'n' when creating BigInt literals

Correct: const bigNumber = 9007199254740991n;

Incorrect: const bigNumber = 9007199254740991; // This is a Number, not a BigInt!

  1. Using the + operator on a combination of numbers and BigInts

Correct: const a = 3n; const b = 5n; const sum = a + bn;

Incorrect: const a = 3; const b = 5n; const sum = a + b; // This will result in a Number, not a BigInt!

  1. Not handling the case when the input is not an integer

Correct:

function factorial(n) {
if (typeof n !== 'bigint' && !Number.isInteger(n)) {
throw new Error('Input must be a non-negative integer');
}
// ... rest of the function
}

Incorrect:

function factorial(n) {
// ... rest of the function (without error handling for non-integer inputs)
}
  1. Performing operations with floating-point numbers and BigInts

Correct: const a = 3n; const b = 5; const sum = BigInt(a + b);

Incorrect: const a = 3n; const b = 5; const sum = a + b; // This will result in a Number, not a BigInt!

Practice Questions

  1. Write a function that calculates the sum of all numbers from 1 to 100 using BigInt arithmetic.
  2. Write a function that checks if a number is even or odd using BigInt arithmetic and conditional statements.
  3. Calculate the factorial of 100! using BigInt arithmetic, and store it in a variable called bigFactorial.
  4. Write a function that multiplies two BigInts without using the multiplication operator (*).
  5. Write a function that checks if a given number is prime using BigInt arithmetic and conditional statements.
  6. Write a function that calculates the Fibonacci sequence up to the nth term using BigInt arithmetic.
  7. Implement an algorithm for finding the square root of a BigInt (note: JavaScript's built-in sqrt() method may not always return exact results).
  8. Write a function that converts a decimal number to a binary string representation using BigInt (hint: use bitwise operations).
  9. Write a function that checks if two BigInts are relatively prime (i.e., their greatest common divisor is 1).
  10. Implement Euclid's algorithm for finding the greatest common divisor of two BigInts.

FAQ

Q: Can I use BigInt with floating-point numbers?

A: No, BigInt is used for integer operations only. If you need to work with large decimal values, consider using the Math.BigDecimal library.

Q: How can I multiply two BigInts without using the multiplication operator (*)?

A: You can use the exponentiation operator (**) to perform multiplication in a roundabout way. For example, a ** 2n is equivalent to a * a.

Q: How do I find the square root of a BigInt?

A: JavaScript does not have built-in support for finding the square root of a BigInt. You can use libraries like mathjs or implement your own algorithm for approximating square roots.

Q: Are there any limitations to using BigInt in JavaScript?

A: While BigInt provides a way to work with large integers, Note that that JavaScript still has some limitations when dealing with very large numbers due to memory constraints and performance considerations. For extremely large integer operations, you may want to consider using other languages better suited for such tasks.

BigInt (JavaScript) | JavaScript | XQA Learn