We are thrilled to inform you that Lancecourse is NOW INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for INITAcademy.org.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 97 – JavaScript BigInt: Handling Large Integers

In this lesson, you'll learn about BigInt, a special numeric type in JavaScript that allows you to work with numbers larger than the Number.MAX_SAFE_INTEGER limit.

Why Use BigInt?

JavaScript’s Number type can only safely represent integers up to:

console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991

Any integer larger than this may lose precision. BigInt solves this problem by allowing storage and manipulation of arbitrarily large integers.

Syntax of BigInt

You can create a BigInt in two main ways:

const big1 = 1234567890123456789012345678901234567890n; // Add "n" at the end
const big2 = BigInt("1234567890123456789012345678901234567890"); // Using the constructor

Key Differences Between Number and BigInt

Feature Number BigInt
Max safe value ±9007199254740991 Arbitrarily large
Type number bigint
Can mix types? Throws error if mixed with BigInt Use explicit conversion

Operations with BigInt

const big1 = 1234567890123456789012345678901234567890n;
const big2 = 1000000000000000000000000000000000000000n;

const sum = big1 + big2;
const diff = big1 - big2;
const product = big1 * 2n;
const quotient = big1 / 3n; // BigInt division truncates decimals

console.log(sum);
console.log(diff);
console.log(product);
console.log(quotient);

Note: You cannot mix Number and BigInt directly:

const result = 10n + 5; // TypeError

Fix with:

const result = 10n + BigInt(5); // OK

Limitations of BigInt

  • Not usable with Web APIs expecting regular numbers (like Math.random()).
  • Can't be used with JSON.stringify directly:
JSON.stringify({ val: 123n }); // Throws error

Practical Use Case

Use BigInt when dealing with cryptography, blockchain applications, or high-precision scientific calculations.

Try Your Hand

  1. Create two very large integers using BigInt.
  2. Add, subtract, multiply, and divide them.
  3. Try converting a Number to BigInt and perform an operation.