8

Possible Duplicate:
What’s the difference between “Array()” and “[]” while declaring a JavaScript array?

In JavaScript you can create a new array like:

var arr = new Array();

or like:

var arr2 = [];

What is the difference and why would you do one over the other?

3
  • As far as I know, it does the same thing. Use whichever you prefer. Commented Feb 4, 2010 at 22:33
  • 5
    Dupe of stackoverflow.com/questions/931872/… Commented Feb 4, 2010 at 22:39
  • wow, insane that the dupe detector didn't detect this when I was asking the question. The questions are nearly identical... Commented Feb 4, 2010 at 22:42

3 Answers 3

4

new Array(2) proudces an array of size 2, containing two undefineds. [2] produces an array of size 1, containing number 2. new Array IMO doesn't fit with the spirit of JavaScript, even though it may make array construction much more findable. That may or may not be of any importance (I use literals almost exclusively in JavaScript for all applicable types, and I've authored/maintained large pieces of JavaScript [30-50 KLOC] successfully).

edit I guess the reasons seasoned javascript programmers avoid new Array syntax are:

  • it doesn't behave uniformly across argument numbers and types ((new Array(X)).length == 1 for any X as long as typeof(X) != "number"
  • it's more verbose and the only thing you gain is the irregularity
Sign up to request clarification or add additional context in comments.

1 Comment

The first bullet point is perfect. That's exactly the kind of thing I was looking for. Thanks!
2

Another (minor) reason to use [] in preference to new Array() is that Array could potentially be overridden (though I've never seen it happen) and [] is guaranteed to work.

Array = "something";
var a = new Array(); // Fails
var b = []; // Works

Comments

0

I believe they're identical. I never use new Array();

2 Comments

Agree, two ways to make the same thing
but WHY don't you use new Array()? I know most "experienced" JavaScript developers don't, but why not?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.