JavaScript BigInt
JavaScript BigInt represent extremely large numbers that go beyond the limits of the standard Number data type.
BigInts are useful in scenarios where precision and range matter, such as cryptography, big data processing, and handling large numeric values
How to Create a BigInt
In JavaScript, you can create a BigInt by appending an "n" to the end of an integer literal or by calling the BigInt() constructor.
Example
const bigIntLiteral = 1234567890123456789012345678901234567890n; const bigIntFromConstructor = BigInt("1234567890123456789012345678901234567890");
BigInt is the second numeric data type in JavaScript (after Number).
With BigInt the total number of supported data types in JavaScript is 8:
- 1. String
- 2. Number
- 3. Bigint
- 4. Boolean
- 5. Undefined
- 6. Null
- 7. Symbol
- 8. Object
BigInt Operators
You can perform arithmetic operations with BigInts just like regular numbers.
Example
const bigInt1 = 1234567890123456789012345678901234567890n; const bigInt2 = 9876543210987654321098765432109876543210n; const sum = bigInt1 + bigInt2; const difference = bigInt1 - bigInt2; const product = bigInt1 * bigInt2; const quotient = bigInt1 / bigInt2;
BigInt Comparison:
You can compare BigInts using relational operators (<, >, <=, >=) and equality operators (==, !=, ===, !==).
Example
const bigInt1 = 1234567890123456789012345678901234567890n; const bigInt2 = 9876543210987654321098765432109876543210n; console.log(bigInt1 < bigInt2); // Output: true
BigInt Conversion:
You can convert a BigInt to a regular number using the Number() function. However, be aware that this may result in loss of precision if the BigInt value is too large.