The remainder operator

The remainder operator (%), also known as the modulo operator, is similar to the division operator. It accepts two operands: a dividend, on the left side, and a divisor on the right side. It will return the remainder following an implied division operation:

10 % 5; // => 0
10 % 4; // => 2
10 % 3; // => 1
10 % 2; // => 0

If the divisor is zero, the dividend is Infinity, or either operand is NaN, then the operation will evaluate to NaN:

Infinity % Infinity; // => NaN
Infinity % 2; // => NaN
NaN % 1; // => NaN
1000 % 0; // => NaN

And if the divisor is Infinity, then the result will be equal to the dividend:

1000 % Infinity; // => 1000
0.03 % Infinity; // => 0.03

The modulo operator is useful in situations where you wish to know whether a number goes into another number squarely, such as when wishing to establish the evenness or oddness of an integer:

function isEvenNumber(number) {
return number % 2 === 0;
}

isEvenNumber(0); // => true
isEvenNumber(1); // => false
isEvenNumber(2); // => true
isEvenNumber(3); // => false

As with all other arithmetic operators, it's useful to be aware of how your operands will be coerced. Most usages of the remainder operator are straightforward, so outside of its coercive behaviors and its treatment of NaN and Infinity, you should find its behavior intuitive.

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

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