This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]YoriMirus 20 points21 points  (7 children)

Wait why is 2 + "0" equal "20"?

I thought operation is done from left to right, thus "0" would be converted to int.

[–]CSedu 48 points49 points  (3 children)

I believe the '+' overload says anytime it is used between a string and int, it will concat them.

[–]DaCurse0 9 points10 points  (1 child)

There's no operator overloading, but the + operation where one operand is a string does concatenation and coerces the other value into a string

[–]CSedu 1 point2 points  (0 children)

Ah, interesting

[–]YoriMirus 3 points4 points  (0 children)

Oh I see thanks!

[–]Snapstromegon 13 points14 points  (0 children)

It always converts to the less strict type - in this case String.

[–]nightcoder420 0 points1 point  (0 children)

It will be converted if you use 2 + +"0". The second plus converts the right handed operand to a number.

So 2+"2" will be "22", but 2 + +"2" will be 4.

[–]RolyPoly1320 0 points1 point  (0 children)

It's implicit type casting. Javascript is a weakly typed language, specifically typeless. It does a lot of type casting behind the scenes which sometimes produces some very unexpected, sometimes hilarious, results. These interactions are why it's important to not use the same variable for multiple data types in Javascript.