25

Possible Duplicate:
What's the difference between Array(1) and new Array(1) in JavaScript?

In javascript, how are these two different?

var arr = Array();  
var arr2 = new Array();

If they are the same according to JS standards, are there any browsers that treat both ways differently?

3
  • 3
    You might use var arr = []; instead. Commented Aug 1, 2011 at 0:37
  • And I don't think in this case it does matter, but we'll see what answers come in. Commented Aug 1, 2011 at 0:41
  • 1
    ... Or, an exact duplicate exists already (big surprise). Commented Aug 1, 2011 at 0:42

2 Answers 2

35

According to ECMA-262 edition 5.1:

15.4.1 The Array Constructor Called as a Function

When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(...) is equivalent to the object creation expression new Array(...) with the same arguments.

The section 11.1.4 (it is quite long, so I won't quote it) also states that array literal directly corresponds to the new Array(...) constructor call.

Sign up to request clarification or add additional context in comments.

4 Comments

... And the answer is... they are equivalent (according to spec). Correct?
Nice. Just look at this answer. I hadn't looked at it, honestly!
What's ECMA-262 edition 5.1? Is it ES5 or ES 10?
Small sidenote for @Alex - ES10 is not a formal version. Since ES2015 (aka ES6) the official yearly version is ES(year). As of today, the latest version is ES2021 (12th edition). The above answer is also confirmed by chapter 23.1.1 The Array Constructor: the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.
3

I believe the 2nd is simply proper coding convention, but however Jared has a good point that most people just use var arr = [];

Here's a benchmark for your question: http://jsperf.com/array-vs-new-array

After 10 runs, they're neck and neck averaging 65-80 millions ops per second. I see no performance difference whatsoever between the two.

That being said, I added var arr = []; to the benchmark, and it is consistently 20-30% faster than the other two, clocking in at well over 120 million ops per second.

2 Comments

I think you've created a corner case where the optimizer is able to guess a lot. I've tried to avoid that... the test crashes my Chromium somehow, through, so I'll just show it to illustrate my point.
Ah okay, it works now. I think that it actually does work the way I think it does.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.