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?

Community
  • 1
  • 1
Davis Dimitriov
  • 4,159
  • 3
  • 31
  • 45

2 Answers2

34

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.

Catherine
  • 22,492
  • 3
  • 32
  • 47
  • 2
    ... And the answer is... they are equivalent (according to spec). Correct? – Jared Farrish Aug 01 '11 at 00:43
  • Nice. Just look at this [answer](http://stackoverflow.com/questions/5827008/whats-the-difference-between-array1-and-new-array1-in-javascript/5827153#5827153). I hadn't looked at it, honestly! – Catherine Aug 01 '11 at 00:46
  • What's ECMA-262 edition 5.1? Is it ES5 or ES 10? – Alex May 02 '20 at 23:56
  • 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](https://262.ecma-international.org/12.0/#sec-array-constructor): ```the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.``` – massic80 Jul 08 '21 at 14:14
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.

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • 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](http://jsperf.com/array-vs-new-array/2) to illustrate my point. – Catherine Aug 01 '11 at 00:56
  • Ah okay, it works now. I think that it actually *does* work the way I think it does. – Catherine Aug 01 '11 at 00:57