16 7 / 2010
Weekend Reading: Subclassing Arrays and Why === Isn’t Always Better Than ==
I came across two very informative articles today, so here is some good weekend reading for you.
The first article is by kangax, and is titled “How ECMAScript 5 still does not allow to subclass an array.” It is a lengthy post that delves into the inability to create a custom array class that inherits methods and functionality from the native Array object while not polluting the native Array object itself. This is very important if you are, for instance, building a library that you do not want other code on the page to be affected by. The article is a good read, and is worth it even if you are not planning on subclassing an Array any time soon.
The second article is more important that all JavaScript coders read. It is by Dmitry Baranovskiy (of RaphaelJS fame), and it discusses the typeof operator as well as the == and === operators: some very misunderstood parts of the JavaScript language. Here are some weird examples:
typeof "hello world" //string
typeof new String("hello world") //object
typeof true //boolean
typeof new Boolean(true) //object
typeof [1, 2, 3] //object
And also for the == and === operators:
new Boolean(true) === true //false
new Boolean(true) == true //true
new String("hello") === "hello" //false
new String("hello") == "hello" //true
Obviously, this could cause some major problems with logic. So, bottom line: be careful with your use of ===. It is not always better than ==. The article is a good read, and provides a nice function that you can use instead of typeof to provide more consistent results.
Enjoy!