📜  javascript bigint - Javascript (1)

📅  最后修改于: 2023-12-03 14:42:23.863000             🧑  作者: Mango

JavaScript BigInt

JavaScript BigInt is a built-in object that provides a way to represent integers larger than the limit of 2^53-1 that is imposed by the Number data type. BigInt data type is introduced in ES2020 which is the latest version of JavaScript standard.

How to use BigInt?

To create a BigInt value, you can add the n suffix to the end of the number, or use the BigInt() constructor function:

const a = 123456789012345678901234567890n;
const b = BigInt("99999999999999999999999999999999999999999");

Any arithmetic operation between a BigInt and a regular Number value is treated as a BigInt operation:

const a = 123456789012345678901234567890n;
const b = 1234567890123456789012345;
console.log(a + b);
// Output: 123456789012345678903469135235n
Operations on BigInt

All the arithmetic operators are supported for BigInt values including addition, subtraction, multiplication, division, and remainder.

const a = 123456789012345678901234567890n;
const b = 9876543210n;
const c = -123456789012345678901234567890n;

console.log(a + b); // Output: 123456789022222222222222222100n
console.log(a - c); // Output: 246913578024691357802469135780n
console.log(a * b); // Output: 1219326321098774392134223517650418479000n
console.log(a / b); // Output: 12500000123n
console.log(a % b); // Output: 8123456780n
Comparison operators with BigInt

All the comparison operators are supported, including less than, greater than, less than or equal to, and greater than or equal to:

const a = 123456789012345678901234567890n;
const b = 9876543210n;
const c = 123456789012345678901234567890n;

console.log(a < b); // Output: false
console.log(a > b); // Output: true
console.log(a <= c); // Output: true
console.log(a >= c); // Output: true
console.log(a === c); // Output: true
console.log(a !== b); // Output: true
Limitations of BigInt

BigInt values cannot be used with some of the built-in JavaScript methods and operators like bitwise operations, left shift operation, and Math object methods.

Also, BigInt values cannot be mixed with regular Number values in the same operation. You need to convert either the BigInt value or the regular Number value into the other type before performing the operation.

Conclusion

BigInt is a powerful and useful feature in JavaScript that allows you to work with integers larger than the limit of Number data type. It is important to keep in mind its limitations when using BigInt in your JavaScript code.

Overall, BigInt is a great addition to the JavaScript language that makes life for developers a lot easier when working with large integers.