JavaScript, by default, uses 64-bit floating-point numbers for representing numbers, which is adequate for most tasks. However, when you need to work with very large integers—beyond the Number
type’s maximum safe integer (2^53 – 1)—JavaScript offers a solution in the form of BigInt. In this tutorial, we’ll dive into the concept of BigInt, its features, how to use it, and practical examples.
1. What is BigInt?
BigInt is a built-in JavaScript object that allows you to represent integers with arbitrary precision. Unlike the traditional Number
type, which is limited to representing integers safely up to 2^53 – 1, BigInt can handle integers of any size, both positive and negative.
Example of Numbers Limits:
- The maximum value for a regular JavaScript
Number
is2^53 - 1
(9007199254740991). - BigInt can go well beyond this limit.
Example:
javascriptCopyEditlet largeNumber = 9007199254740992n; // The 'n' suffix indicates BigInt
console.log(largeNumber); // Output: 9007199254740992n
Note the n
at the end of the number, which distinguishes a BigInt from a regular number.
2. Creating BigInts
There are two ways to create BigInt values in JavaScript:
- Using the BigInt Constructor: You can pass a string or a number to the
BigInt()
constructor. javascriptCopyEditlet bigInt1 = BigInt(123456789012345678901234567890); // Using BigInt constructor let bigInt2 = BigInt("123456789012345678901234567890"); // Using a string console.log(bigInt1); // Output: 123456789012345678901234567890n
- Using the
n
Suffix: Simply append then
character to a numeric literal. javascriptCopyEditlet bigInt3 = 123456789012345678901234567890n; // With 'n' suffix console.log(bigInt3); // Output: 123456789012345678901234567890n
3. Basic Operations with BigInt
BigInt supports most mathematical operations that regular numbers do, such as addition, subtraction, multiplication, division, and modulo.
Example:
javascriptCopyEditlet a = 1000n;
let b = 500n;
let sum = a + b; // Addition
let difference = a - b; // Subtraction
let product = a * b; // Multiplication
let quotient = a / b; // Division
let remainder = a % b; // Modulo
console.log(sum); // 1500n
console.log(difference); // 500n
console.log(product); // 500000n
console.log(quotient); // 2n
console.log(remainder); // 0n
Note that BigInt division always returns an integer result, truncating any fractional part.
4. BigInt and Number Compatibility
JavaScript does not allow automatic mixing of BigInt
and Number
types in mathematical operations. For instance, trying to add a Number
and BigInt
will throw a TypeError
.
Example:
javascriptCopyEditlet num = 10;
let bigInt = 20n;
let result = num + bigInt; // TypeError: Cannot mix BigInt and other types
To resolve this issue, you can either convert the Number
to a BigInt
, or convert the BigInt
to a Number
.
Converting a Number
to BigInt
:
javascriptCopyEditlet sum = BigInt(num) + bigInt;
console.log(sum); // Output: 30n
Converting a BigInt
to Number
(be cautious about precision loss for large numbers):
javascriptCopyEditlet numberSum = Number(bigInt) + num;
console.log(numberSum); // Output: 30 (but precision might be lost for very large numbers)
5. Comparison Operations with BigInt
You can compare BigInt values using comparison operators like >
, <
, >=
, <=
, ===
, and !==
, just like with regular numbers.
Example:
javascriptCopyEditlet big1 = 100n;
let big2 = 200n;
console.log(big1 > big2); // Output: false
console.log(big1 < big2); // Output: true
console.log(big1 === big2); // Output: false
6. Handling BigInt in JSON
BigInt values are not directly supported in JSON, so if you attempt to serialize a BigInt with JSON.stringify()
, it will be converted to undefined
.
Example:
javascriptCopyEditlet bigIntValue = 123456789012345678901234567890n;
let jsonString = JSON.stringify({ bigIntValue });
console.log(jsonString); // Output: {"bigIntValue":undefined}
To handle BigInts in JSON, you can convert them to strings before serializing and convert them back afterward.
javascriptCopyEditlet obj = { bigIntValue: bigIntValue.toString() };
let jsonString = JSON.stringify(obj);
// Parse JSON and convert back to BigInt
let parsedObj = JSON.parse(jsonString);
parsedObj.bigIntValue = BigInt(parsedObj.bigIntValue);
console.log(parsedObj); // Output: { bigIntValue: 123456789012345678901234567890n }
7. BigInt Performance Considerations
Since BigInt values can grow arbitrarily large, performing operations on them can be slower compared to regular numbers, especially for very large numbers. When performance is a concern, ensure that you really need the precision that BigInt provides.
8. When to Use BigInt
BigInt is useful when:
- You are dealing with integers beyond the safe range of JavaScript’s
Number
type (i.e., larger than9007199254740991
or smaller than-9007199254740991
). - You are working with cryptography, large-scale computations, or other domains that require very large integers.
If you don’t need numbers beyond the Number
range, sticking with regular numbers can offer better performance.
9. Conclusion
BigInt is a powerful addition to JavaScript, allowing you to handle very large integers beyond the limitations of the traditional Number
type. While it’s easy to use and supports most arithmetic and comparison operations, keep in mind that it doesn’t mix automatically with regular numbers and can have performance overhead for extremely large values. When working with cryptography, scientific calculations, or any domain requiring large numbers, BigInt is an invaluable tool. Happy coding!