Why does Javascript only type-cast for string concatenation on strings that are already assigned?

Tags: , , , ,



I noticed something strange when messing around with strings and numbers in a Javascript console. Doing this:

"$99.9" += 0

causes SyntaxError: Invalid left-hand side in assignment. But if I assign the string to a variable, the behavior is different (and more in line with what we’ve come to expect/accept from Javascript)

let str = "$99.9"

str += 0 // => "$99.90"

I’m familiar with what causes the behavior in the second example (and what causes so many other Javascripty things to happen), but the error in the first example surprised me. What is happening in the first example of this that stops the usual Javascript behavior?

Answer

that’s because you can only assign value to variable. In your case, you are trying to assign a value to a string. Litterally. The += operator translate to variable = variable + 0. In your case it translate to this : "$99.9" = "$99.9" + 0 and “$99.9” is not a variable nor a valid variable name.
In the second case, you are assigning the “$99.9” value to a variable THEN using the += operator to change the variable value.



Source: stackoverflow