Core JavaScript 1.5 Guide:Operators:Arithmetic Operators
From MDC
[edit] Arithmetic Operators
Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces NaN). For example:
1 / 2 // returns 0.5 in JavaScript 1 / 2 // returns 0 in Java (neither number is explicitly a floating point number) 1.0 / 2.0 // returns 0.5 in both JavaScript and Java
In addition, JavaScript provides the arithmetic operators listed in the following table.
| Operator | Description | Example |
|---|---|---|
| % (Modulus) |
Binary operator. Returns the integer remainder of dividing the two operands. | 12 % 5 returns 2. |
| ++ (Increment) |
Unary operator. Adds one to its operand. If used as a prefix operator (++x), returns the value of its operand after adding one; if used as a postfix operator (x++), returns the value of its operand before adding one. | If x is 3, then ++x sets x to 4 and returns 4, whereas x++ returns 3 and, only then, sets x to 4. |
| -- (Decrement) |
Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. | If x is 3, then --x sets x to 2 and returns 2, whereas x-- returns 3 and, only then, sets x to 2. |
| - (Unary negation) |
Unary operator. Returns the negation of its operand. | If x is 3, then -x returns -3. |
Table 3.4: Arithmetic Operators