ECMAScript Additive Operators
- Previous Page Multiplicative Operators
- Next Page Relational Operators
In most programming languages, the addition operator (i.e., the plus or minus sign) is usually the simplest mathematical operator.
In ECMAScript, the addition operator has a lot of special behaviors.
Addition operator
The arithmetic operator is represented by the plus sign (+):
var iResult = 1 + 2
Like the multiplicative operator, addition in ECMAScript has some special behaviors when dealing with special values:
- If an operand is NaN, the result is NaN.
- -Infinity plus -Infinity results in -Infinity.
- Infinity plus -Infinity results in NaN.
- +0 plus +0, the result is +0.
- -0 plus +0, the result is +0.
- -0 plus -0, the result is -0.
However, if an operand is a string, the following rules apply:
- If both operands are strings, concatenate the second string to the first one.
- If only one operand is a string, convert the other operand to a string, and the result is the concatenation of the two strings.
For example:
var result = 5 + 5; //Two numbers alert(result); //Output "10" var result2 = 5 + "5"; //One number and one string alert(result2); //Output "55"
This code illustrates the difference between the two modes of the addition operator. Normally, 5+5 equals 10 (original value), as shown in the first two lines of the above code. However, if one of the operands is changed to the string "5", the result will be "55" (original string value), because the other operand will also be converted to a string.
Note:To avoid a common error in JavaScript, always check the data type of the operands when using the addition operator.
Subtraction Operator
The subtraction operator (-) is also a commonly used operator:
var iResult = 2 - 1;
Like the addition operator, the subtraction operator also has some special behaviors when dealing with special values:
- If an operand is NaN, the result is NaN.
- Infinity minus Infinity, the result is NaN.
- -Infinity minus -Infinity, the result is NaN.
- Infinity minus -Infinity, the result is Infinity.
- -Infinity minus Infinity, the result is -Infinity.
- +0 minus +0, the result is +0.
- -0 minus -0, the result is -0.
- +0 minus -0, the result is +0.
- If an operand is not a number, the result is NaN.
Note:If both operands are numbers, perform a regular subtraction operation and return the result.
- Previous Page Multiplicative Operators
- Next Page Relational Operators