How does JavaScript handle Divide by Zero?
Overview
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.
How do programming languages handle it?
Most programming languages throw an exception at run time. For handling the exception, they use a try-catch block.
How does JavaScript handle it?
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:
- JavaScript is a dynamically typed language, and it performs
type-coercion. - Throwing exceptions at runtime is inconvenient for JavaScript.
So, how does JavaScript evaluate these expressions?
Let’s see that in the following example.
Example
// Declare and initialize a number with 0const num1 = 0;// Declare and initialize a number with a positive integerconst num2 = 10;// Declare and initialize a number with a negative integerconst num3 = -10;// Divide by zero with a zeroconsole.log("Divide by zero with a zero:", num1 / 0);// Divide by zero with a positive integerconsole.log("Divide by zero with a positive integer:", num2 / 0);// Divide by zero with a negative integerconsole.log("Divide by zero with a negative integer:", num3 / 0);
Explanation
- Line 2: We declare and initialize a variable
num1with 0. - Line 5: We declare and initialize a variable
num2with a positive value. - Line 8: We declare and initialize a variable
num3with a negative value. - Line 11: We divide the variable
num1with 0, and print the output on the console. - Line 14: We divide the variable
num2with 0, and print the output on the console. - Line 17: We divide the variable
num3with 0, and print the output on the console.
Output
The output of the code in JavaScript is as follows:
- Dividing the number 0 by 0 returns NaN.
- Dividing the positive number by 0 returns Infinity.
- Dividing the negative number by 0 returns -Infinity.