The addition operator (+
) adds numbers.
var a = 9,
b = 3,
c = a + b;
c
will now be 12
This operand can also be used multiple times in a single assignment:
var a = 9,
b = 3,
c = 8,
d = a + b + c;
d
will now be 20.
Both operands are converted to primitive types. Then, if either one is a string, they're both converted to strings and concatenated. Otherwise, they're both converted to numbers and added.
null + null; // 0
null + undefined; // NaN
null + {}; // "null[object Object]"
null + ''; // "null"
If the operands are a string and a number, the number is converted to a string and then they're concatenated, which may lead to unexpected results when working with strings that look numeric.
"123" + 1; // "1231" (not 124)
If a boolean value is given in place of any of the number values, the boolean value is converted to a number (0
for false
, 1
for true
) before the sum is calculated:
true + 1; // 2
false + 5; // 5
null + 1; // 1
undefined + 1; // NaN
If a boolean value is given alongside a string value, the boolean value is converted to a string instead:
true + "1"; // "true1"
false + "bar"; // "falsebar"