The addition operator
+ performs addition or concatenates strings. When you’re dealing with just numbers or just strings, the results are intuitive.
// Number + String -> concatenation 1 + 'foo' = '1foo' '5' + 5 = '55'
Another gotcha is that operators are evaluated from left to right. Consider the example below with its output.
1 + 2 + '3' + 4 + 5 // '3345'
Moving from left to right, we add
1 + 2 which is
3. Then we see the string
'3', so we have string concatenation, resulting in
'33'. Now that we have a string, we concatenate
5 as if they, too, were strings, resulting in
The subtraction operator subtracts two operands. If they are numbers, the behavior is expected.
10 - 5 // 5 5 - 10 // -5
If you perform subtraction with a string, the result will usually be
NaN (Not a Number).
5 - 'foo' // NaN 'bar' - 10 // NaN
10 - '5' // 5 '5' - '10' // -5 '10' - '.' - '5' // NaN because '.' can't be converted into a number