In case of operation
1 + '1'
,
the number 1 is converted to string and appended to the later string then why isn't it the case for
1 * '1'
There is no difference between the numbers 01 and 1 . They are absolutely identical.
1 Answer. This happens when one or both of the variables is String which results in string concatenation. The arithmetic operators like / * - performs a toNumber conversion on the string(s). In order to convert a string to a number : use the unary + operator.
The Number() method converts a value to a number. If the value cannot be converted, NaN is returned.
Because +
is overloaded.
+
can mean either addition or string concatenation. In the former case, JavaScript attempts to do string concatenation rather than addition, so it converts everything to a string and carries out the string concatenation. In the latter case, the only option is to multiply, so it converts everything to something that can be multiplied and carries out the multiplication.
dfsq linked the specification of addition syntax in the comments under your question, which explains why JS attempts string concatenation instead of addition: It checks whether the things you're adding together are strings, and then if at least one of them is, attempts string concatenation - and otherwise, attempts addition.
The +
is a concatenation operator for strings. As a result, the number gets converted to a string and then concatenated. The concatenation takes preference over numeric addition. If you want to make it add them instead, use parseInt, like 1 + parseInt('1')
The *
is not a valid operator for strings at all, so it converts the string to a number and then does the operation.
This is a simple case, so the order of operands don't matter. If you get more complex, it tends to get even more interesting. For instance:
1 + 1 + '1' = '21'
'1' + 1 + 1 = '111'
For more information, check out this MDN article on the matter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With