JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript BigInt

8 April 2025 | Category:

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 with Number 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

FeatureDescription
123nBigInt literal
BigInt("12345")Convert string to BigInt
typeof 123nReturns "bigint"
DivisionAlways rounds down
Math methods❌ Not compatible
Mixed with Number❌ Throws TypeError