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
andBigInt
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
- Create two very large integers using
BigInt
. - Add, subtract, multiply, and divide them.
- Try converting a
Number
toBigInt
and perform an operation.