JavaScript RangeError: BigInt divison by Zero
Last Updated :
05 Jun, 2023
In JavaScript, the BigInt type was introduced to represent integers with arbitrary precision. This means that BigInt can represent very large numbers, but it also means that BigInt must follow certain mathematical rules. In particular, division by zero is mathematically undefined and impossible. Attempting to perform division by zero will result in an error in most programming languages, including JavaScript.
When you attempt to divide a BigInt by zero in JavaScript, a runtime error will be generated. The JavaScript engine will recognize that the divisor is zero and raise a RangeError with the message “BigInt divide by zero“. This is similar to what happens when you attempt to divide a regular number by zero, which is also mathematically undefined and will result in a runtime error.
It’s important to note that in JavaScript, the BigInt type and the regular Number type behave differently when dividing by zero. If you divide a regular Number by zero, the result will be Infinity or –Infinity, depending on the sign of the number. However, as we’ve seen, attempting to divide a BigInt by zero will always result in a RangeError.
Return Value:
RangeError: Division by zero (V8-based)
RangeError: BigInt division by zero (Firefox)
Error Type:
RangeError
Cause of the Error: The result of dividing any number by zero is undefined, and it results in a ZeroDivisionError. This is because dividing by zero would result in an infinite or undefined value.
Example:
Javascript
const x = 1n;
const y = 0n;
const quotient = x / y;
console.log(quotient) ;
|
Output
RangeError: BigInt division by zero
If you want to avoid this type of error, just check if the divisor is 0n first, and either issue an error with a better message, or fallback to a different value, like Infinity or undefined.
Example:
Javascript
const x = 1n;
const y = 0n;
const quotient = y === 0n ? undefined : x / y;
console.log(quotient);
|
Output:
undefined
Example 3:
Javascript
const x = BigInt(12345);
const y = BigInt(0);
const result = x / y;
|
Output:
RangeError: BigInt divide by zero
Share your thoughts in the comments
Please Login to comment...