Operator Penambahan ECMAScript
- Previous Page Multiplicative Operators
- Next Page Relational Operators
Dalam sebagian besar bahasa pemrograman, operator penjumlahan (yaitu tanda plus atau minus) biasanya adalah operator matematika paling sederhana.
Dalam ECMAScript, operator penjumlahan memiliki banyak perilaku khusus.
Operator penjumlahan
Operator penjumlahan ditandai dengan tanda plus (+):
var iResult = 1 + 2
Sama seperti operator perkalian, dalam menghandle nilai khusus, penambahan dalam ECMAScript memiliki beberapa perilaku khusus:
- If an operand is NaN, the result is NaN.
- -Infinity ditambah -Infinity, hasilnya -Infinity.
- Infinity ditambah -Infinity, hasilnya 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, then follow the following rules:
- If both operands are strings, concatenate the second string to the first.
- 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 demonstrates 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 become "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 carefully 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 the operands are all numbers, then perform the regular subtraction operation and return the result.
- Previous Page Multiplicative Operators
- Next Page Relational Operators