62 points · by co_pl_te · 13y ago · 87 comments
[1] == [1] is false, but [1] == 1 and 1 == [1]?
[0] == [0] is false, but [0] == '0' and '0' == [0]?
[] == [] is false but [] == 0 and 0 == []?
NaN === NaN is false?
[0] + [0] = '00', but [0] * [0] = 0?
Who designed this crazy language? It seems to take every quirk of every other language and combine them in the weirdest way possible.
[] == [] is false, so it must be comparing pointers, right? Common gotcha of Java, etc.
...Wait, NaN === NaN is false.
[1] != [1] since both [1] are distinct arrays; [1] == 1 since 1 is primitive so [1] gets converted to primitive, in this case, '1', and '1' == 1. (The conversion to primitive is complicated, mainly because it has to select between ToNumber and ToString depending on the context. See Section 9.1 of ECMA-262 5th edition.) Likewise, [] == 0 since [] gets converted to '' and coerced to 0.
NaN != NaN is a well-known facet of IEEE 754 floating point system, and you'll see similar phenomenon in SQL's NULL handling.
[0] + [0] == '00' since both operands are coerced to string (no numeric operands there, so we assume both operands will eventually become string); [0] * [0] == 0 since both operands are coerced to number (no multiplication on string).
...Yeah, I agree on your thesis that ECMA-262 is seriously f*cked up.
As for the rest of those quirks, they mainly have to do with type coercion, the rules for which are not as difficult to learn as the whole table in the submission. The fact that type coercion is performed for == is why nobody uses ==. You also should never try + or * on arrays (and why would you?). With some simple best practices, you never end up running into most of these quirks in practice.
in a NaN === NaN world, (1/0)*0 === 0/0 is true.
I kinda makes sense if you consider that both 0/0 and Infinity0 evaluate to NaN. `0/0 == Infinity0` being true would be an even weirder behaviour.
The lesson is, always look for a method that does what you want.
Whether one can avoid it or not is a different argument, as obviously there aren't that many choices on the browser, but I often argue it is a broken behavior, it annoys me every time I have to use Javascript.
The real mistake was making [] equal zero.
So a simple fraction type can be done like this:
function Fraction(n, d) {
this.n = n;
this.d = d;
}
Fraction.prototype.toString = function() {
return this.n / this.d;
};
//Demo
var x = new Fraction(1, 2);
alert(x * 38); //19
alert(x + x); //1[].length is what you want for the second. IIRC [] isn't false in Python either.
>>> if (): print "tuple"
>>> if []: print "list"
>>> if {}: print "dict"
>>> if set(): print "set"
>>> if "": print "string"
>>> import collections
>>> if collections.Counter(): print "counter"
>>> if collections.deque(): print "deque"
>>>
(Observe that none of these prints anything.)It might as well be.
Unfortunately, "JavaScript" isn't in the list.
If you come from a static language background and you keep expecting a type-checker will save you from doing silly things like adding arrays to strings, you're always going to hate Javascript. It's a dynamically typed language, and so you have to learn the quality-control tools and practices for dynamically typed languages.
Hmm funny I come from a dynamic language background and never had a problem with the language telling me adding an empty list to an empty list should somehow be empty string. That is batshit crazy. Those are not silly things those are basic 101 strong type system checks that very dynamics languages like Ruby and Python can do.
As you move beyond native types, duck-typing (like in python) completely subverts the strong type-checks anyway.
I don't think being a dynamically typed language has anything to do with having weird type coercion rules for the most basic operations. Nor with allowing seemingly invalid operations (e.g. adding arrays and strings) and returning a value instead of raising an error on those cases.
> I honestly have no idea what's so confusing.
Really? Comparing JS's == and + operators to other languages' (dynamically typed or not), wouldn't you say that JS's semantics are more complicated/confusing than what they should be?
>>> '5' < [6]
true '1' == 1
'1' == [1]
'1' == true
1 == [1]
1 == true
[1] == true
But this is false: [1] == [1]It is funny that you are asking why would [1] == [1] possibly considered to be true.
Let's see in a language with a sane and consistent typing system like Python:
In [1]: [1]==[1]
Out[1]: True
Ok, let's do a crazy language from Sweden also with dynamic types but which are sane and consistent, like Erlang: 1> [1] == [1].
true
Surely it will be broken in Ruby: irb(main):001:0> [1] == [1]
=> true
Nah clearly it should be false, these crazy languages just haven't heard about objects and identities and such.[1] == 1 and 1 == [1], so it should be the case that [1] == [1].
Just because it's what happens when you apply the rules of the language doesn't mean it actually makes sense.
This is because you require the programmer to always understand the output (and defaults) of every call made. Sometimes it's undefined. Sometimes it's null. Sometimes it's empty string. This takes experience.
Example, the default for getAttribute is null, but an undefined property is undefined:
document.body.getAttribute("test"); // null
document.body.test; // undefined
Except if it's a special property, then getAttribute might still be null, but the property empty string: var input = document.createElement("input");
input.getAttribute("value"); // null
input.value; // ""
Remember, "" !== null and null !== undefined. 5 + (10 * [2]) + (9 + [1/'']) // 259Infinity
5 ~+ (10 ~* [2]) ~+ (9 ~+ [1 ~/ '']) // throw exception`[null] + {} == 'null[object Object]'`? Okay, fine. I might not have known that off the top of my head, but I also make it a habit not to add/concat arrays and objects.
Unexpected type coercion is probably responsible for about 1% of the bugs I write. It's just not that big of a deal once you learn the common cases (`'1' == 1`, etc.)
Now, I understand that javascript runs in a completely different kind of environment, and it does have the liberty of making things differently, up to a certain point. But making '' == 0 true may be a bit too far.. And making [1] == 1 true is clearly too far.
define "clean" and name one language in the history of computing that actually fits that definition.
'Evolved' languages tend to be less clean than 'designed' ones, and also any language accumulates cruft with time if features are added carelessly - for example, C++ can never be 'clean' even if C++11 tries to be that way, because compatibility.
Python, go, Haskell are much cleaner than JS. I'm not claiming that those languages are perfect, they definitely aren't, but there is a significant difference - just as in the saying that [earth is flat] is wrong, [earth is a sphere] is wrong, but they're nowhere near equally wrong.
EDIT: removed Java, Rust and Go
For another, if you put lua in the browser instead of javascript, how long do you think it will be before lua starts growing horrible warts as well?
It's too late now because it would break a lot of applications, so a new mode might be required, like "use not-completely-broken-comparisons-by-default".
> Seibel: I was reading Java Puzzlers and Effective Java and it struck me that there are a lot of little weird corners for a language that started out so simple.
> Bloch: There are weird corners, yes, but that's just a fact of life; all languages have them. You haven't seen a book called C Puzzlers. Why not?
> Seibel: Because it's all puzzlers.
> Bloch: Yep. It would take up a shelf. In Java, the puzzlers are worth collecting precisely because you think of it as a simple language. Every language has its corner cases and Java has few enough that they're for the most part fun and interesting.
Interesting, maybe. But I hope people are not using all of these. [0]
> a === b
true
> Number(a) === a
true
> Number(b) === b
true
> a + b === a
true
> (1 / a) === (1 / b)
false
0 and -0.
I never knew about this until I read a shim someone wrote for Object.is().
It was for a similar reason that many people used to like XHTML over HTML. Not always because they needed to validate it, but to please the computer.
Yes.
Because programs, unless they deal with machine learning, statistics or other intentional approximations, deal with _strict_ things.
If you put $0.5 in an account you don't expect to find $0.2 there when you read it back or find "Hi Jim" there. You expect to find $0.5, when you seek to byte offset 19553 in the file you expect to read starting with byte 19553 on next read not "something in the vicinity of byte 19553".
[] + [] should not be '', never, it never makes sense, it is not brilliant it is rather profoundly stupid.
Ok, language is broken, we established it, let's take a look at the library functions. At least there cooler heads prevailed:
$ node
> [1,10,9,-3,-4].sort()
[ -3, -4, 1, 10, 9 ]
Nope, they didn't. > [1, 4, 9].map(sqrt)
[1, 2, 3]
> ['1', '2', '3'].map(parseInt)
[1, NaN, NaN]
cf. http://stackoverflow.com/questions/262427/javascript-arrayma...I'm not actually all that impressed by this illustration of Javascript's equality rules. This makes it look crazy when in fact it just gives the many edge cases much stronger visual weight.
The truth is, Javascript has lent strongly toward being natural in many of the most common cases -- things like being able to do `args = args || []` or simply prepending `!` to anything. Then, sometimes when you end up comparing NaN to undefined you aren't sure what the result should be or how you ended up there.
Funny thing is that often when I've run into those problems myself, I pull on the thread and find it was really caused by my own poor design somewhere else.
They do? How can I stop them all?
Programmers want code to be readable to an IDE.
IDE's can parse, interpret, precompile, and suggest.
Languages that are very wishy washy and dynamic like javascript are absolute hell for an IDE.
It's one of the biggest weaknesses of JavaScript. Much bigger than callback hell, garbage collection cycles etc.
My preferred style uses Array.prototype.join('') for string concatenation, non-coercive equality operations, and only using the + operator when doing math. It's a little cumbersome, but avoids ambiguity upon reading (and in the case of string concatenation, can be faster).
Weak typing and automatic coercions lead to some confusing results, but JS fares better than PHP.