The following code gives weird results:
console.log("" + 1 + 10 + 2 - 5 + "8");
I've tried inputting various different values to work it out but I cannot understand what's going on under the hood.
The following code gives weird results:
I've tried inputting various different values to work it out but I cannot understand what's going on under the hood. |
||||
In JavaScript, the When you use the When you then "add" a string |
|||||||||
|
string + number = concatenated string number + number = the sum of both numbers string - number = the difference between (coerced string) and the number explanation:If one or both operands is string, then the plus is considered as string concatenation operator rather than adding numbers. the minus operator always try to convert both operands to numbers. so:
|
|||||
|
SNIPPET
|
||||
|
This site has some useful info.
|
|||
|
While As In this case, as the operator precedence is the same, and the evaluation is from left to right, you end up with (""+1+10+2) using Perhaps an interesting alternative would have been ""+1+10+2-5+8, which would have been 1097+8, or the number 1105. |
|||
|
[javascript] addition string number
– Felix Kling 18 hours ago