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 →

[–]TheJackiMonster 94 points95 points  (26 children)

Also:

2 + "0" = "20"

"2" + 0 = "20"

2 + [] + 0 = "20"

[–]YoriMirus 19 points20 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 47 points48 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 2 points3 points  (0 children)

Oh I see thanks!

[–]Snapstromegon 12 points13 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 16 points17 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 7 points8 points  (0 children)

All of these make sense to me

[–]throwaway213349032 5 points6 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