JavaScript BigInt
What is BigInt?
in JavaScript, BigInt is a special type of number that can represent very large integers — larger than what the regular Number type can safely store.
BigInt can handle numbers beyond 2^53 - 1 (9007199254740991) — which is the maximum safe integer for normal numbers.
BigInt was introduced in ES11 (2020).
Creating a BigInt
There are two ways to create a BigInt:
1. Adding n at the end
let bigNumber = 1234567890123456789012345678901234567890n;
2. Using the BigInt() function
let bigNum = BigInt("1234567890123456789012345678901234567890");
Both methods create a BigInt.
Example and Outputs
let x = 1234567890123456789012345678901234567890n;
console.log(x); // Output: 1234567890123456789012345678901234567890n
let y = BigInt(9876543210);
console.log(y); // Output: 9876543210n
Why BigInt is Needed
JavaScript's regular numbers (Number type) are based on the IEEE 754 double-precision format, which cannot safely represent integers beyond:
console.log(Number.MAX_SAFE_INTEGER); // Output: 9007199254740991
Trying to go beyond that causes precision problems:
console.log(9007199254740991 + 1); // Output: 9007199254740992
console.log(9007199254740991 + 2); // Output: 9007199254740992
(WRONG!)
With BigInt, you can safely handle even larger numbers:
let big = 9007199254740991n + 2n;
console.log(big); // Output: 9007199254740993n
Important Rules with BigInt
1. Can't mix BigInt and Number directly
let a = 5n;
let b = 2;
console.log(a + b); // TypeError: Cannot mix BigInt and other types
To fix it, you must convert one type:
console.log(a + BigInt(b)); // Output: 7n
2. BigInt is for integers only
- BigInt cannot have decimal points.
let x = 5.5n; // SyntaxError: Cannot use a decimal point
3. Comparisons with Number
You can compare BigInt and Number safely:
console.log(5n == 5); // true (loose equality)
console.log(5n === 5); // false (strict equality, because types are
different)
console.log(5n > 3); // true
Always prefer === to avoid confusion.
Example:
let a = 10n;
let b = 3n;
console.log(a + b); // Output: 13n
console.log(a - b); // Output: 7n
console.log(a * b); // Output: 30n
console.log(a / b); // Output: 3n (no decimals!)
console.log(a % b); // Output: 1n
Quick Recap
- BigInt is used for very large integers.
- Add n at the end (100n) or use BigInt() function.
- Cannot mix BigInt and Number directly.
- No decimal values are allowed in BigInt.
- Operations like +, - , * , /, % work on BigInts.
Example Summary
let large = 123456789012345678901234567890n;
console.log(large); // 123456789012345678901234567890n
console.log(typeof large); // "bigint"
let sum = 1000n + 2000n;
console.log(sum); // 3000n