Best way to prevent/handle divide by 0 in javascript

Active3 hr before
Viewed126 times

7 Answers


what would be the best way to handle such a situation so as to not prevent other scripts from executing, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,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?,Thanks for contributing an answer to Stack Overflow!

The best way to do what you want is with guards:

function notZero(n) {
   n = +n; // Coerce to number.
   if (!n) { // Matches +0, -0, NaN
      throw new Error('Invalid dividend ' + n);
   return n;

and then do division like

numerator / notZero(denominator)

Alternatively you can always guard the output

function dividend(numerator, denominator) {
   var quotient = numerator / denominator;
   if (quotient !== quotient) {
      throw new Error(numerator + " / " + denominator);
   return quotient;
load more v

This article has explored some of the idiosyncrasies of numbers in JavaScript. Hopefully, you now understand why these issues arise, and how you can avoid them. And, although you may not run into cases like the negative zero very often, at least now you are prepared.,Instead of using the comparison operators, you can test for NaN using the isNaN() function, as shown below.,To make matters worse, JavaScript’s comparison operators can’t seem to tell the two values apart either, as shown in the following example.,Note – Before reading this article, you should have a basic familiarity with JavaScript data types.

In JavaScript, all numbers are represented using the Number data type. This includes integers, real numbers, hexadecimal numbers, and numbers written in scientific notation. The following example verifies this by applying the typeof operator to a variety of numbers. Each application of typeof in this example returns number.

load more v

Division by zero gives an error of type arith-error which can be caught in the usual ways with condition-case and similar. A division by zero example can be found in the Elisp manual section "Handling Errors". ,In contrast, integer division by zero raises an exception which can be caught as follows: ,Integer divison (that is, div and not /) by zero will cause min to exit with an uncatchable arithmetic error. ,In FreeBASIC integer division by zero is a fatal error and cannot be caught by the language's built-in error handling constructs.

Division by zero results in the value "Inf":

1 0 n: / Inf? . cr 
load more v

The division operator (/) produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor. , Advanced Inheritance and the prototype chain Strict mode JavaScript typed arrays Memory Management Concurrency model and Event Loop , JavaScript Guide Introduction Grammar and types Control flow and error handling Loops and iteration Functions Expressions and operators Numbers and dates Text formatting Regular expressions Indexed collections Keyed collections Working with objects Details of the object model Using promises Iterators and generators Meta programming JavaScript modules ,SyntaxError: applying the 'delete' operator to an unqualified name is deprecated

x / y
load more v

Wrapping up the freeCodeCamp metric-imperial converter project, I discovered a strange bug. A possible user input is a fractional number w/unit such as 3/4mi. However, there is a possibility a user could input 3/0mi. Decided to test this out in the console and got the following: ,The global isFinite() function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.,It looks to be the expected answer, but I noticed something. Dividing by a negative zero results in a negative Infinity. Not sure what that means, I decided to check the ECMAScript.,DEV Community – A constructive and inclusive social network for software developers. With you every step of your journey.

3 / 0
// Infinity
load more v

We can handle this exception in a number of different ways, some of which are listed below,We use Exception Handling to overcome exceptions occurred in execution of a program in a systematic manner.,How to store a very large number of more than 100 digits in C++,Subtraction of two numbers using 2's Complement

load more v

@AnyhowStep reminder that there are many NaNs in IEEE 754 floats, and JS adds its own layer of bizarreness on top:,Could we define real, a subset of number which excludes Infinity or nan?,Interesting. It appears nothing actually breaks until something needs and actual number. It would be cool if Infinity and NaN could be considered separate types.,Given an equivalent to Flow's $Call (I'm gonna use regular function syntax for this), I'd imagine a TS equivalent to be implemented like declare function div<B extends number, NotZero = { (v: '1') => 'whatever'; }(B extends 0 ? '0' : '1')>(a: number, b: B).

function f(): number | 0 {
   return 0

const y = 100 / f()
load more v

Other "prevent-javascript" queries related to "Best way to prevent/handle divide by 0 in javascript"