Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you declare an array without New in Javascript? [duplicate]

Tags:

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?

like image 782
Davis Dimitriov Avatar asked Aug 01 '11 00:08

Davis Dimitriov


People also ask

What will happen if you declare an array without its size?

Even if you do not initialize the array, the Java compiler will not give any error. Normally, when the array is not initialized, the compiler assigns default values to each element of the array according to the data type of the element.

Why does changing an array in JavaScript affect copies of the array?

An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.


2 Answers

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.

like image 116
whitequark Avatar answered Oct 10 '22 03:10

whitequark


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.

like image 26
AlienWebguy Avatar answered Oct 10 '22 03:10

AlienWebguy