Andreas Grech Andreas Grech - 8 months ago 29
Javascript Question

In JavaScript, why is [ ] preferred over new Array();?

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();

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 a reason on why
is better than
new Array();

var Array = function () { };

Overriding the
object will break code...!

Any more reasons ?



It has less bytes to transfer over the wire, less bytes to interpret, less mental resources to parse it.

Less is more.


What is the difference between these two lines of code?

var arr = [5];
var arr = new Array(5);

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 being undefined. Whereas these two lines return identical arrays.

var arr = [5,6];
var arr = new Array(5,6);