What is the best way to prevent divide by 0 in javascript that is accepting user inputs. If there is no particular way to achieve this what would be the best way to handle such a situation so as to not prevent other scripts from executing?
Any insights are much appreciated.
There is no way to do that with the normal
/
and/=
operators.The best way to do what you want is with guards:
and then do division like
Alternatively you can always guard the output
but that loses the readability and expressiveness of
/=
.To prevent (unwanted) execution
return false;
as value to stop submission.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
try/catch
.Off the top of my head you could:
isFinite()
and if not then handle appropriately.Division by zero doesn't seem to prevent other scripts from execution in JavaScript:
If you want something different to happen in case of division by zero, you could use
A bit different than stopping execution, but the ternary operator is a pretty slick way to customize variable assignment.
This way, by setting the customVariable to the integer of your choice, you can expect a predictable result when division by zero occurs.