Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  190] [ 3]  / answers: 1 / hits: 31634  / 10 Years ago, thu, july 31, 2014, 12:00:00

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'


More From » javascript

 Answers
23

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.


[#69981] Tuesday, July 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
melinal

Total Points: 367
Total Questions: 101
Total Answers: 96

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
;