10Feb/101
JavaScript Arrays – new Array() vs array literal

Do not every say new Array() when creating a new JavaScript Array(). There are differences between creating an array in Javascript using the array literal, or the fully qualified "object" name (Array() vs []), and the bottom line is that the "right" way to do it is "[]" (array literal) instead of "new Array()". Here is why:
- Most experienced JS programmers use []. [] 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 plain vanilla JavaScript Objects (which, yes they are in-so-much as they are Objects with extra 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)






September 11th, 2012 - 04:50
Nice post!
I always thought the reason for using brackets instead of new was only commodity and minification advantages, so thanks for the info.
By the way, there’s one more plus to using the array literal: it’s faster ( http://jsperf.com/new-array-vs-square-brackets/5 ). Even though the difference it’s not that great at this scale, it still counts for something