💥 BigInt in JavaScript
🔢 What is BigInt?
BigInt is a built-in JavaScript primitive used to represent **whole numbers larger than 253 - 1**, which is the maximum safe integer for the Number type. It allows you to work with arbitrarily large integers without losing precision.
Note
BigInts are used **only for integers**, not for floating-point numbers.
🧪 Creating BigInts
You can create BigInts in two ways:
Code Snippet
const big1 = 1234567890123456789012345678901234567890n;
const big2 = BigInt("1234567890123456789012345678901234567890");Note
You must suffix the number with n or use the BigInt() constructor.
➕ Arithmetic with BigInt
Use standard operators: +, -, *, /, **, etc.
Code Snippet
const a = 123456789012345678901234567890n;
const b = 987654321098765432109876543210n;
console.log(a + b); // Addition
console.log(b - a); // Subtraction
console.log(a * b); // Multiplication
console.log(b / a); // Division (rounded down)
console.log(b % a); // RemainderNote
Division with BigInt will always round **down** toward zero.
⚠️ Cannot Mix BigInt and Number
You cannot directly mix BigInt and regular Number types in operations:
Code Snippet
const x = 10n;
const y = 5;
console.log(x + BigInt(y)); // ✅ Convert Number to BigInt
console.log(Number(x) + y); // ✅ Convert BigInt to Number
console.log(x + y); // ❌ TypeError: Cannot mix BigInt and other types🔎 Comparing BigInt
Comparisons with == or ===:
Code Snippet
console.log(10n == 10); // true (loose equality)
console.log(10n === 10); // false (strict equality)
console.log(10n > 5); // true📚 BigInt with JSON
JSON.stringify() does **not support** BigInt by default.
Code Snippet
const big = 123456789012345678901234567890n;
JSON.stringify(big); // ❌ Throws TypeErrorNote
If you need to serialize a BigInt, convert it to a string first.
🧪 Use Cases
- Cryptography
- Working with large financial figures
- High-precision timestamps
🧾 Summary
- BigInt handles large integers beyond Number.MAX_SAFE_INTEGER.
- Use n suffix or BigInt() constructor to create them.
- Cannot mix BigInt and Number in expressions directly.
- JSON.stringify doesn't support BigInt out of the box.
>>“Use BigInt when precision matters more than performance.”