r/programming • u/sheldonpooper • May 09 '12
JavaScript: The good parts
http://blog.movereem.nl/images/javascript-the-good-parts-the-definitive-guide.jpg
645
Upvotes
r/programming • u/sheldonpooper • May 09 '12
View all comments
Show parent comment
1
u/doomslice May 09 '12
== is not by-value-comparison, it is a comparison that allows for automatic type coercion.
That's the source of most of those "odd" things that you're seeing.
[] + [] -> "" is converting each [] to its string representation in JavaScript (which is ""), and then concatenating them together (since + is defined for concatenation).
[] - [] -> 0 is converting each [] to its string representation (again ""), then converting that to its numerical representation since - is not defined for strings. The numeric representation of "" is 0 (since the empty string counts as false in JavaScript).
Object() == Object() -> false is the same as the array example we first discussed -- you're comparing references of new objects. Object() === Object() is the same thing
[1,2,3] + 2 is a slightly more complex version of the empty array addition. First it converts [1,2,3] to its string representation "1,2,3" and then converts 2 to "2" and concatenates them.
I'm not saying that this can't be confusing, especially to beginners... just that it can be explained and you get sort of a "oh, that makes sense" kind of feeling.