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'
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'
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
+
is used for string concatenation
*
is used for multiplicatio
In 1 + '1' '+' will concatenate 1 with '1'
You need to do following
1 + parseInt('1')
In javascript + indicates concatination. That's why when you try to add a number(i.e. 1) to a string ('1'),it becomes 11. And it treats * as multipication, so it multiplies a number (1) with a string ('1') and gives result as 1. e.g. (1*a= a).
"+" Operator is used for both string concatenation and normal mathematical addition so when we use this operator between a number and string it will just concatenate those two. But "*" Operator not like that it will only perform multiplication if this used between a number and a pure string it wont give proper output.But, if it is used between a number and again a number in string format it will consider both as number and give the multiplication of those two.