04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3: Language Basics<br />

Modulus<br />

The modulus (remainder) operator is represented by a percent sign ( % ) and is used in the following way:<br />

var result = 26 % 5; //equal to 1<br />

Just like the other multiplicative operators, the modulus operator behaves differently for special values,<br />

as follows:<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

If the operands are numbers, regular arithmetic division is performed, and the remainder of that<br />

division is returned.<br />

If the dividend is Infinity or the divisor is 0, the result is NaN .<br />

If Infinity is divided by Infinity , the result is NaN .<br />

If the divisor is an infinite number, the result is the dividend.<br />

If the dividend is zero, the result is zero.<br />

If either operand isn ’ t a number, it is converted to a number behind the scenes using Number()<br />

and then the other rules are applied.<br />

Additive Operators<br />

Add<br />

The additive operators, add and subtract, are typically the simplest mathematical operators in<br />

programming languages. In ECMAScript, however, a number of special behaviors are associated with<br />

each operator. As with the multiplicative operators, conversions occur behind the scenes for different<br />

data types. For these operators, however, the rules aren ’ t as straightforward.<br />

The add operator ( + ) is used just as one would expect, as shown in the following example:<br />

var result = 1 + 2;<br />

If the two operands are numbers, they perform an arithmetic add and return the result according to the<br />

following rules:<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

If either number is NaN , the result is NaN .<br />

If Infinity is added to Infinity , the result is Infinity .<br />

If – Infinity is added to – Infinity , the result is – Infinity .<br />

If Infinity is added to – Infinity , the result is NaN .<br />

If +0 is added to +0, the result is +0.<br />

If – 0 is added to +0, the result is +0.<br />

If – 0 is added to – 0, the result is – 0.<br />

56

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!