I remember reading somewhere (I think it was in one of Crockford's papers) that using an array literal []
is better than using the new Array();
notation.
But I can't really remember any advantages of one over the other.
Can anyone please explain to me on why the former is preferred over the latter?
Here is one reason I can think of on why []
is better than new Array();
:
var Array = function () { };
Overriding the Array
object will break code...!
Any more reasons?
new Array(1, 2, 3)
instead of[1, 2, 3]
is the same asnew String("cow")
instead of"cow"
Brevity
It has less bytes to transfer over the wire, less bytes to interpret, less mental resources to parse it.
Less is more.
Consistency
What is the difference between these two lines of code?
According to here
new Array(5);
will not return an array with a 5 in it, instead it will return a 5 element array, with all the elements beingundefined
. Whereas these two lines return identical arrays.Elegance
To put it simply it just looks nicer AND is easier for a programmer to parse, especially for more complicated data structures:
Versus the clumsier OOP-oriented method:
One good reason is because the Array constructor has completely non-intuitive behavior. For example:
In this case, a ends up being an array of size 5 with all elements undefined, and b ends up being an array of size 2, with the values [1,2].
And here, you end up with a single-element array, containing "5"
In general, you should probably never use the constructors on built-in types in Javascript. They all have weird edge cases like this. For example: