Divide by Zero is considered a special case by most programming languages. Any number can never be divided by zero because its result is indeterminate. This shot covers how JavaScript handles a Divide by Zero expression.
Most programming languages throw an exception
at run time. For handling the exception, they use a try-catch block.
JavaScript acts differently from other programming languages. When it encounters any Divide by Zero expression, it doesn’t throw an exception.
Now, the question may arise of why JavaScript behaves differently and why it doesn’t throw any exception.
The possible reasons for this are as follows:
type-coercion
.So, how does JavaScript evaluate these expressions?
Let’s see that in the following example.
// Declare and initialize a number with 0 const num1 = 0; // Declare and initialize a number with a positive integer const num2 = 10; // Declare and initialize a number with a negative integer const num3 = -10; // Divide by zero with a zero console.log("Divide by zero with a zero:", num1 / 0); // Divide by zero with a positive integer console.log("Divide by zero with a positive integer:", num2 / 0); // Divide by zero with a negative integer console.log("Divide by zero with a negative integer:", num3 / 0);
num1
with 0.num2
with a positive value.num3
with a negative value.num1
with 0, and print the output on the console.num2
with 0, and print the output on the console.num3
with 0, and print the output on the console.The output of the code in JavaScript is as follows:
RELATED TAGS
CONTRIBUTOR
View all Courses