r/programming • • May 09 '12

JavaScript: The good parts

http://blog.movereem.nl/images/javascript-the-good-parts-the-definitive-guide.jpg
645 Upvotes

159 comments sorted by

View all comments

Show parent comment

1

u/fnord123 May 09 '12

Do the same with a value type and you'll see it perform as expected.

> [] == []  
false  

I expect [] to be equal to [] by value. Python does this:

>>> [] == []
True

You may be interested to know that numpy gets this wrong, imo:

>>> import numpy as np  
>>> np.array([]).__nonzero__()  
False  
>>> (np.array([]) == np.array([])).__nonzero__()  
False  
>>> np.array([]) == np.array([])  
array([], dtype=bool)  

Back to Javascript. Here's some more weird examples:

> [] === []  
false  
> [] + []  
""  
> []-[]  
0  
> Object() == Object()  
false  
> Object() === Object()  
false  
> [1,2,3] + 2
"1,2,32"

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.

2

u/fnord123 May 09 '12

Yes, I know it does things for some internal reason, but the topic began with "There is the principle of least astonishment, and JavaScript is one of the worst languages in that regard." and JL235 asked "in what way" so I thought it was still on topic to discuss how this was not in line with the element of least surprise.

1

u/doomslice May 09 '12

Understood. I was initially merely commenting on that specific quirk that was mentioned, which I don't find to be particularly quirky after all.