Today, I found an unexpected behaviour of JavaScript while I was using the +
operator :
"a" + "" //returns "a"
"a" + + "" //returns "a0"
Why does the second expression yield "a0"
?
The +
symbol is used for multiple operators and operations:
a + b
where a
or b
is a string performs concatenation. If the other value is not a string it is converted to one.a + b
where a
and b
are numbers performs addition.++a
or a++
performs incrementation (increase by one).+ a
which is the unary positive operator, which takes a number and returns it unchanged. This is sometimes used by programmers as a shortcut to convert a string to a number.JavaScript automatically converts types when one of these operations is encountered with other or mixed data types. Objects and arrays tend to convert to strings automatically, and concatenation has priority over addition. This is why number + object
returns a string, which might not make sense at first if you expected +
to represent addition.
In conclusion, the interpreter guesses the operation based on its context. If you write "a" + + ""
, it sees two +
operators in a row. Since these can't both be binary operators, it understands that the second +
is the unary +
, which converts a string to a number. The empty string automatically converts to 0
because the unary +
only works with numbers, and then the other +
sees a string and a number. Since there's a string, it converts the other operand to a string and performs concatenation.