JavaScript - BigInt: Handling Really Big Numbers

Hello there, aspiring coders! Today, we're going to embark on an exciting journey into the world of really, really big numbers in JavaScript. Buckle up, because we're about to explore the fascinating realm of BigInt!

JavaScript - BigInt

What is BigInt?

Imagine you're counting stars in the night sky. You count and count, but suddenly your calculator says "Infinity". Frustrating, right? That's where BigInt comes to the rescue!

BigInt is a special numeric type in JavaScript that can represent integers of arbitrary length. Unlike regular numbers, which have limitations, BigInt can handle numbers as large as your imagination (or your computer's memory) allows.

Why do we need BigInt?

In JavaScript, regular numbers are stored in 64 bits, which means they have a maximum safe integer value of 9,007,199,254,740,991. That's a big number, but in the world of computing, sometimes we need to go even bigger!

Let's see what happens when we try to exceed this limit:

console.log(9007199254740991 + 1); // 9007199254740992
console.log(9007199254740991 + 2); // 9007199254740992 (Oops! Same result)

As you can see, JavaScript can't accurately represent numbers beyond this limit. This is where BigInt shines!

Declaration and Initialization

Creating a BigInt is as easy as pie. You have two options:

  1. Append 'n' to the end of an integer
  2. Use the BigInt() function

Let's try both:

const bigNumber1 = 1234567890123456789012345678901234567890n;
const bigNumber2 = BigInt("9007199254740991");

console.log(bigNumber1); // 1234567890123456789012345678901234567890n
console.log(bigNumber2); // 9007199254740991n

Notice the 'n' at the end? That's how JavaScript knows it's a BigInt!

Basic Operations

Now that we have our big numbers, let's do some math!

const a = 1234567890n;
const b = 9876543210n;

console.log(a + b);  // 11111111100n
console.log(a - b);  // -8641975320n
console.log(a * b);  // 12193263111263526900n
console.log(a / b);  // 0n (Integer division)
console.log(a % b);  // 1234567890n

Remember, BigInts are always whole numbers. When dividing, the result is rounded down to the nearest integer.

Comparison

Comparing BigInts is just like comparing regular numbers:

console.log(5n > 4n);   // true
console.log(5n < 4n);   // false
console.log(5n === 5);  // false (different types)
console.log(5n == 5);   // true (type coercion)

Notice the last two lines. BigInts and regular numbers are considered equal when using ==, but not when using ===. This is because === checks for both value and type equality.

Conversions

Sometimes you'll need to convert between BigInts and regular numbers. Here's how:

const bigNum = 123456789n;
const regularNum = Number(bigNum);

console.log(regularNum);  // 123456789

const backToBigInt = BigInt(regularNum);
console.log(backToBigInt);  // 123456789n

Be careful when converting large BigInts to regular numbers, as you might lose precision!

Examples

Let's put our BigInt knowledge to use with some real-world examples:

1. Calculating Factorials

function factorial(n) {
    if (n === 0n) return 1n;
    return n * factorial(n - 1n);
}

console.log(factorial(20n));  // 2432902008176640000n

This function can calculate factorials of much larger numbers than would be possible with regular JavaScript numbers!

2. Working with Really Large Prime Numbers

function isPrime(n) {
    if (n <= 1n) return false;
    for (let i = 2n; i * i <= n; i++) {
        if (n % i === 0n) return false;
    }
    return true;
}

const largeNumber = 2n ** 100n - 1n;
console.log(isPrime(largeNumber) ? "Prime" : "Not Prime");  // Not Prime

This function can check primality for numbers far beyond the limits of regular JavaScript numbers!

Error Handling with BigInt

When working with BigInts, there are a few things to watch out for:

try {
    const result = 1n + 1;  // This will throw an error
} catch (error) {
    console.log("Error:", error.message);  // Cannot mix BigInt and other types
}

try {
    const result = Math.sqrt(4n);  // This will also throw an error
} catch (error) {
    console.log("Error:", error.message);  // Cannot convert a BigInt value to a number
}

Remember, BigInts can only be used with other BigInts for arithmetic operations, and many Math functions don't support BigInts.

BigInt Methods

Here's a table of the most commonly used BigInt methods:

Method Description Example
BigInt() Creates a BigInt value BigInt(123)
BigInt.asIntN() Wraps a BigInt value to a signed integer between -2^(n-1) and 2^(n-1)-1 BigInt.asIntN(3, 5n) // 5n
BigInt.asUintN() Wraps a BigInt value to an unsigned integer between 0 and 2^n-1 BigInt.asUintN(3, 5n) // 5n
BigInt.prototype.toString() Returns a string representation of a BigInt value (123n).toString() // "123"
BigInt.prototype.valueOf() Returns the primitive value of a BigInt object Object(123n).valueOf() // 123n

And there you have it, folks! You're now equipped to handle numbers bigger than the stars in the sky. Remember, with great power comes great responsibility - use your BigInts wisely!

Happy coding, and may your numbers always be as big as your dreams!

Credits: Image by storyset