18

I read at many tutorials that the current best practices to create a new javascript array is to use

var arr = [] 

instead of

var arr = new Array()

What's the reasoning behind that?

Praveen
  • 55,303
  • 33
  • 133
  • 164
AlfaTeK
  • 7,487
  • 14
  • 49
  • 90

5 Answers5

13

It might be because the Array object can be overwritten in JavaScript but the array literal notation cannot. See this answer for an example

Community
  • 1
  • 1
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
  • 3
    This depends per implementation though. At least in the past [] used the Array constructor in some JS engines (iirc there was a fuzz about scripts being able to capture array creation for JSONP requests by overriding the array constructor). – reko_t May 31 '10 at 15:18
  • @reko_t - that's very true. I know in Firefox the array literal doesn't use the Array constructor, not sure of the others (no way to check at the moment, could someone confirm?) – Russ Cam May 31 '10 at 15:22
  • Would someone be able to fix the link please? iPhone editing is tricky :) – Russ Cam May 31 '10 at 15:23
  • Already did it 2 mins ago, Sean did it once again the minute thereafter. – BalusC May 31 '10 at 15:24
12

Also note that doing:

var x = [5];

Is different than doing:

var x = new Array(5);

The former creates an initializes an array with one element with value of 5. The later creates an initializes an array with 5 undefined elements.

reko_t
  • 55,302
  • 10
  • 87
  • 77
3

It's less typing, which in my book always wins :-)

Once I fixed a weird bug on one of our pages. The page wanted to create a list of numeric database keys as a Javascript array. The keys were always large integers (a high bit was always set as an indicator). The original code looked like:

 var ids = new Array(${the.list});

Well, guess what happened when the list had only one value in it?

 var ids = new Array(200010123);

which means, "create an array and initialize it so that there are 200 million empty entries".

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • oh well whatever - I can't recall exactly what the IDs looked like, but it was big enough to cause an immediate out-of-memory – Pointy May 31 '10 at 15:36
1

Usually an array literal(var a=[1,2,3] or a=[]) is the way to go.

But once in a while you need an array where the length itself is the defining feature of the array.

var A=Array(n) would (using a literal) need two expressions-

var A=[]; A.length=n;

In any event, you do not need the 'new' operator with the Array constructor, not in the way that you DO need 'new' with a new Date object, say.

kennebec
  • 102,654
  • 32
  • 106
  • 127
1

To create Array without Length

var arr = [];

To create Array with Length more dynamically

var arr;
( arr = [] ).length = 10;  // 10 is array length

To create Array with Length less dynamically

var arr = [];
arr.length = 10;