Hướng dẫn javascript divide by zero
Shubham Singh Kshatriya
OverviewDivide 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 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:
So, how does JavaScript evaluate these expressions? Let’s see that in the following example. 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); Explanation
OutputThe output of the code in JavaScript is as follows:
RELATED TAGS javascript divide by zero js communitycreator CONTRIBUTOR Shubham Singh Kshatriya The best way is contextual. But here's the easiest:
Basically if the input is zero, turn it into a very small number before using as a denominator. Works great for integers, since after your division you can round them back down. A couple caveats prevent this from being universal:
So it's best for general-purpose, non-critical cases. For example, if you need to return the result of a complex calculation and don't care if the answer is accurate to N digits (determined by 0.0001 vs. 0.00000001, etc.); you just don't want it to break on a divide-by-zero. As another answer suggested, you could also create a reusable global function.
Possible improvements:
This would take any value (null, number, string,
object) and if invalid or zero, return the failsafe zero-like value. It would also coerce the output to a number just in case it was a string and you were doing something odd. All this would ensure that your divisor function always worked. Finally, for cases where you wanted to handle such errors yourself, you could set the second parameter to true and use a |