The division operator

The division operator, much like the subtraction operator, accepts two operands that it will coerce to numbers. It will divide its left-side operand by its right-side operand:

10 / 2; // => 5

The two operands are formally called the dividend and the divisor (DIVIDEND / DIVISOR) and will always evaluate according to floating-point math. Integer division does not exist in JavaScript, which means, effectively, that the results of your divisions may always include decimal points, and may hence be liable to the error margin of Number.EPSILON.

Watch out when dividing by zero, as you may end up with either NaN (when dividing zero by zero) or Infinity (when dividing a non-zero number by zero):

10 / 0;  // => Infinity
10 / -0; // => -Infinity
0 / 0; // => NaN

If your divisor is Infinity, your division will always evaluate to zero (0 or -0), unless your dividend is also Infinity, in which case, you'll receive NaN:

1000 / Infinity; // => 0
-1000 / Infinity; // => -0
Infinity / Infinity; // => NaN

In circumstances where you expect a divisor or dividend of zero, NaN or Infinity, it is best to be defensive and either check for those values explicitly beforehand or following the operation, like so:

function safeDivision(a, b) {
const result = a / b;
if (!isFinite(result)) {
throw Error(`Division of ${a} by ${b} is unsafe`);
}
return result;
}

safeDivision(1, 0); // ! Throws "Division of 1 by 0 is unsafe"
safeDivision(6, 2); // => 3

The edge cases of division may seem scary but they're not frequently encountered in everyday applications. If we were, however, authoring a medical or financial program, then it'd be absolutely vital to carefully consider our operations' potential error states. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.252.204