Creating BigInt Values
To create a BigInt value, you simply append the letter ‘n’ to the end of an integer literal or use the BigInt() function. For example:
const bigNum = 1234567890123456789012345678901234567890n;
const bigNum = BigInt("1234567890123456789012345678901234567890");
Operations with BigInts
The basic arithmetic operations like addition, subtraction, multiplication, and division can be performed on BigInts just like regular numbers. Here are a few examples:
const result = bigNum1 + bigNum2;
const result = bigNum1 - bigNum2;
const result = bigNum1 * bigNum2;
const result = bigNum1 / bigNum2;
When performing arithmetic operations on BigInts, the result will always be a BigInt. However, mixing BigInts with regular numbers in arithmetic operations will result in a TypeError. To perform operations between BigInts and regular numbers, you need to convert one of them beforehand using the BigInt() function.
Comparison and Equality
To compare BigInts, you can use the usual comparison operators like
!=. Here are a few examples:
bigNum1 > bigNum2;
bigNum1 === bigNum2;
bigNum1 != bigNum2;
Supported Operations and Methods
The BigInt data type supports various built-in methods such as:
toString(): Returns the string representation of the number.
toLocaleString(): Returns a string representing the number according to local conventions.
valueOf(): Returns the primitive value of the number.
Limits and Considerations
While BigInt allows you to work with arbitrarily large numbers, it is important to note that it comes with some limitations:
- Memory Usage: Working with large BigInt values requires more memory compared to regular numbers.
- No Automatic Conversion: Unlike regular numbers, BigInts are not automatically converted to other types in operations.
- No Bitwise Operations: Bitwise operations like shifting and logical operators are not supported for BigInts.