JavaScript BigInt
8 April 2025 | Category: JavaScript
JavaScript’s regular Number
type can safely store values between -(2^53 - 1)
and 2^53 - 1
. But what if you need to work with very large integers beyond this range?
That’s where BigInt comes in.
✅ What is BigInt?
BigInt is a special data type in JavaScript used to represent integers larger than 2⁵³ – 1 (9007199254740991
) — the maximum safe integer in JavaScript.
let big = 1234567890123456789012345678901234567890n;
console.log(big);
The
n
at the end tells JavaScript it’s a BigInt.
📏 Max Safe Integer in JavaScript
console.log(Number.MAX_SAFE_INTEGER);
// Output: 9007199254740991
Going beyond this with regular numbers can cause precision errors:
let unsafe = 9007199254740991 + 1;
console.log(unsafe); // 9007199254740992 ❌ (Might be inaccurate)
🔹 Creating BigInts
✅ Using n
suffix:
let big = 123456789123456789123456789n;
✅ Using BigInt()
constructor:
let big = BigInt("123456789123456789123456789");
🔹 Operations with BigInt
You can use all basic math operators:
let x = 12345678901234567890n;
let y = 98765432109876543210n;
console.log(x + y); // Addition
console.log(y - x); // Subtraction
console.log(x * 2n); // Multiplication
console.log(y / x); // Division (rounded down)
⚠️ Note: You must use
BigInt
values on both sides — mixing withNumber
causes an error.
let x = 10n;
let y = 5;
console.log(x + BigInt(y)); // ✅
console.log(x + y); // ❌ TypeError
🔹 BigInt Division Rounds Down
console.log(10n / 3n); // Output: 3n (no decimals!)
🔹 Type of BigInt
console.log(typeof 123n); // Output: "bigint"
🔹 Limitations of BigInt
- ❌ Can’t use with
Math
methods (Math.sqrt()
,Math.pow()
, etc.) - ❌ Cannot mix with regular
Number
types directly - ❌ Not suitable for decimals or floating-point math
🧠 When Should You Use BigInt?
Use BigInt when:
- You’re working with cryptography
- You need precise large IDs or big numbers
- You’re dealing with scientific calculations
✅ Summary Table
Feature | Description |
---|---|
123n | BigInt literal |
BigInt("12345") | Convert string to BigInt |
typeof 123n | Returns "bigint" |
Division | Always rounds down |
Math methods | ❌ Not compatible |
Mixed with Number | ❌ Throws TypeError |