About Lesson
JavaScript BigInt
BigInt is a new data type in JavaScript that can represent integers of arbitrary precision. It allows you to work with extremely large numbers that cannot be accurately represented using the traditional number
data type.
Creating BigInt
To create a BigInt, append an n
suffix to an integer literal, or use the BigInt()
constructor.
Example:
const bigInt1 = 123456789012345678901234567890n;
const bigInt2 = BigInt("123456789012345678901234567890");
console.log(bigInt1); // Output: 123456789012345678901234567890
console.log(bigInt2); // Output: 123456789012345678901234567890
Arithmetic Operations
You can perform arithmetic operations on BigInts just like regular numbers.
Example:
const bigInt1 = 123456789012345678901234567890n;
const bigInt2 = 987654321098765432109876543210n;
const result = bigInt1 + bigInt2;
console.log(result); // Output: 1111111110111111111011111111100
Comparison
BigInts can be compared using comparison operators like >
, <
, ==
, etc.
Example:
const bigInt1 = 123456789012345678901234567890n;
const bigInt2 = 987654321098765432109876543210n;
console.log(bigInt1 > bigInt2); // Output: false
console.log(bigInt1 === bigInt2); // Output: false
BigInts provide a way to work with extremely large numbers in JavaScript, allowing for precise arithmetic operations without losing precision.