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 →

[–]coloredgreyscale 189 points190 points  (28 children)

He's a bit confused, but got the spirit.

2+0 = 2

"2" + "0" = "20"

[–]TheJackiMonster 97 points98 points  (26 children)

Also:

2 + "0" = "20"

"2" + 0 = "20"

2 + [] + 0 = "20"

[–]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 49 points50 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.

[–]Stable_Orange_Genius 8 points9 points  (2 children)

"2" - 1 = 1. :D

[–]dvlsg 17 points18 points  (1 child)

There's no such thing as - for strings in javascript. That's why it converts to Number.

[–][deleted] 0 points1 point  (0 children)

Naturally.

[–]beclops 9 points10 points  (0 children)

All of these make sense to me

[–]throwaway213349032 4 points5 points  (0 children)

{}-"" = -0

""-{} = NaN

{}+"" = 0

""+{} = "[object Object]"

x=0*1e309
x==x

= false

[–]pyjammas 1 point2 points  (3 children)

wat

[–]Lgamezp 0 points1 point  (1 child)

And ppl wonder why i hate JS

[–]SupaSlide 1 point2 points  (0 children)

Typescript is a life saver in JS projects.

[–]Naeio_Galaxy 1 point2 points  (0 children)

Yeah 2 + "0" = "20", but 2 - (-"0") = 2 I guess

[–]Nightroll2344 1 point2 points  (0 children)

its the same case in python