Did a little research recently about the difference between creating an array in Javascript using the array literal, or the fully qualified “object” name (Array() vs []). Here is what I found:
- Most experienced JS programmers use []. This is what I was told by Paul Irish. When I asked Paul what he thought of a JS book I was reading, he immediately looked for an array definition (which ended up being Array() instead of []) and pointed it out as being “old fashioned”. [] is the way Douglas Crockford teaches it in JavaScript the Good Parts (they even talk about it in JavaScript the Definitive Guide). Also, if you look in the unminified source for the jQuery library, you will never see Array().
- They appear to be nearly identical, except they aren’t.
- [] is more terse and readable, especially for nested arrays:
vs:
- Using the Array() keyword makes you think about arrays as being somehow different from Objects (which, yes they are in-so-much as they are Objects with actual methods already defined for you). The literal helps you think about them more object-like because [] looks like {}. Plus, [] is more consistent with the way that you then access the array something[0] so there is less to remember.
- Most importantly, Array() doesn’t behave uniformly across argument numbers and types. ((new Array(X)).length === 1 for any X as long as typeof(X) != “number” else Array(X).length === X)
ChomperStomp
Hallelujah Button
Status-bar Calculator
Andy Harris' Books
Outer Spice Web Company
Paul Irish's Blog
The Daily WTF
yayQuery Podcast