JavaScript BigInt() Constructor
Last Updated :
16 May, 2023
The JavaScript BigInt BigInt() Constructor is used to convert any primitive data type or object to a BigInt data type. It returns a new BigInt object that represents the original value. This method is particularly useful when dealing with large numbers that exceed the safe integer limit of 9007199254740991.
Syntax:
BigInt(value);
Parameters: The BigInt() Constructor takes one parameter, which is the value that needs to be converted to a BigInt data type.
Note: This parameter can be a primitive data type such as a number, string, or boolean, or it can be an object.
Return Value: The BigInt() Constructor returns a new BigInt object that represents the original value passed as a parameter.
Example 1: Fibonacci Sequence with BigInt: In this example, we will create a function to generate the Fibonacci sequence up to a given index using BigInt. We will use the BigInt.bigInt() method to convert numbers to BigInt, as the Fibonacci sequence grows rapidly and exceeds the maximum safe integer size.
JavaScript
// This function calculates the
// Fibonacci sequence up to a
// given number 'n'
function fibonacci(n) {
let sequence = [0n, 1n];
for (let i = 2; i <= n; i++) {
sequence[i] = BigInt(sequence[i - 1])
+ BigInt(sequence[i - 2]);
}
return sequence;
}
console.log(fibonacci(10));
Output[
0n, 1n, 1n, 2n, 3n,
5n, 8n, 13n, 21n, 34n,
55n
]
Example 2: Calculating Large Factorials with BigInt: In this example, we will create a function to calculate the factorial of a large number using BigInt. We will use the BigInt.bigInt() method to convert numbers to BigInt, as factorials can be very large.
JavaScript
// This function calculates the
// Factorial of given number 'n'
function factorial(n) {
let result = 1n;
for (let i = 2n; i <= n; i++) {
result *= BigInt(i);
}
return result;
}
console.log(factorial(30));
Output265252859812191058636308480000000n
Example 3: Large Number Exponentiation with BigInt: In this example, we will create a function that calculates the value of a large number raised to a large power. We will use the BigInt.bigInt() method to convert numbers to BigInt, as both the base and exponent can be very large.
JavaScript
// This function calculates the Power
// of given base and exponent
function power(base, exponent) {
let result = 1n;
for (let i = 0n; i < exponent; i++) {
result *= BigInt(base);
}
return result;
}
console.log(power("123456789", 10));
Output822526259147102579504761143661535547764137892295514168093701699676416207799736601n
Supported Browsers:
- Chrome 67.0
- Edge 79.0
- Firefox 68.0
- Opera 54.0
- Safari 14.0