JavaScript Arithmetic Operators
JavaScript’s arithmetic operators perform addition (+), subtraction (-), multiplication (*), and division (/). Mozilla has a great overview of them, but it fails to mention any of the edge cases that frequently trip up developers new to JavaScript.
Addition (+)
The addition operator +
performs addition or concatenates strings. When you’re dealing with just numbers or just strings, the results are intuitive.
// Number + Number -> addition
1 + 2 // 3
5 + 50 // 55
// String + String -> concatenation
'hello' + ' there' // 'hello there'
'Java' + 'Script' // 'JavaScript'
But when you combine numbers and strings, the numbers will be turned into strings and concatenated. This is a typical gotcha when learning JavaScript.
// 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 4
and 5
as if they, too, were strings, resulting in 3345
.
Subtraction (-)
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
But due to JavaScript’s type coercion, the interpreter will try to convert a string into a number. Which leads to unexpected results:
10 - '5' // 5
'5' - '10' // -5
'10' - '.' - '5' // NaN because '.' can't be converted into a number
Want to improve your JavaScript? I have a list of recommended JavaScript books. <!– ## Division (/)