JavaScript horrors
by mithrandi on Dec.30, 2008
Okay, so you probably already know JavaScript is bad; but did you know exactly how bad? Here’s a couple of my favourite examples; if you haven’t seen all of these already, then hopefully you’ll also be saved some future headaches by reading this. Please note that I am using = to denote the concept of structural equality, since there isn’t really any JavaScript operator that maps to that concept.
String coercion:
"5" + "10" = "510" 5 + "10" = "510" "5" + 10 = "510" 5 + 10 = 15
[1,2,3] + 4 = "1,2,34" 1 + [2,3,4] = "12,3,4"
null + "foo" = "nullfoo" undefined + "foo" = "undefinedfoo" null + [1,2] = "null1,2" undefined + [1,2] = "undefined1,2" null + null = 0 undefined + undefined = NaN
Array constructor:
Array("1", "2", "3") = ["1", "2", "3"]
Array(1, 2, 3) = [1, 2, 3]
Array(4) = [undefined, undefined, undefined, undefined]
“Equality”:
1 == 1 = true 1 == 2 = false 1 == "1" = true [1] == 1 = true [1,2] == "1,2" = true [1,2,3] == [1,2,3] = false var x = [1,2,3]; x == x = true null == undefined = true null == "null" = false