JavaScript BigInt
BigInt is a special numeric type that allows you to represent integers of arbitrary length. It is useful for handling values too large to fit into a standard JavaScript Number.
Key Topics
- Creating BigInt
- Operations with BigInt
- Mixing BigInt and Number
- JavaScript Usage in DOM
- Key Takeaways
Creating BigInt
Append n
to the end of an integer or use the BigInt()
function to create a BigInt value.
let bigNum = 123456789012345678901234567890n;
console.log(typeof bigNum);
Output
> bigint
Explanation: Using n
at the end of the number creates a BigInt, and typeof
confirms its type as "bigint"
.
Operations with BigInt
You can perform arithmetic operations on BigInt values, similar to regular numbers, but both operands must be BigInt.
let a = 1000000000000000000n;
let b = 2n;
console.log(a * b);
Output
> 2000000000000000000n
Explanation: Multiplying two BigInts produces a BigInt result without losing precision.
Mixing BigInt and Number
You cannot mix BigInt and regular Number in arithmetic operations. Convert one type to the other if necessary.
let big = 10n;
let num = 5;
// console.log(big + num); // Error
console.log(big + BigInt(num));
Output
> 15n
Explanation: Converting num
to a BigInt with BigInt(num)
allows the addition operation without error.
JavaScript Usage in DOM
This DOM-based example demonstrates using BigInt to handle large values and display them on the webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BigInt in DOM</title>
</head>
<body>
<h1>BigInt Demo</h1>
<button onclick="showBigInt()">Show Big Number</button>
<p id="info"></p>
<script>
function showBigInt() {
let largeValue = 9999999999999999999999999999n;
document.getElementById("info").textContent = "Large Value: " + largeValue;
}
</script>
</body>
</html>
Key Takeaways
- BigInt: Represent integers beyond Number's safe range.
- Arithmetic: Perform precise math on very large integers.
- Type Conversion: Convert between Number and BigInt before mixing.
- DOM Usage: Display large integer values on webpages without loss of precision.