Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to write: var arr=[]; than var arr=new Array();? [duplicate]

Tags:

javascript

Is it better to write

var arr=[]; then var arr=new Array(); 
var obj={}; then var obj=new Object();

and if so, why?

I read slide lection page 36 about that idea, but no explanation was given or example why its better.

like image 663
Ben Avatar asked Aug 02 '10 08:08

Ben


2 Answers

There is not a big difference between these definitions, except that the first way uses the array/object literal and the second the array/object constructor.

The array constructor may return different results, depending on the number of arguments passed in. If you pass in one argument, a new empty array is created of the length of that argument. For example:

// arr1 is the same as arr2
var arr1 = new Array(1, 2, 3, 4);
var arr2 = [1, 2, 3, 4];

alert(arr1.length == arr2.length); // true
alert(arr1[0]); // 1
alert(arr2[0]); // 1

But, passing in one argument results differently:

// arr3 has length 200 and is empty, while arr4 has length 1 and contains a number
var arr3 = new Array(200);
var arr4 = [200];

alert(arr3.length == arr4.length); // false
alert(arr3[0]); // 'undefined'
alert(arr4[0]); // 200

The speediest way to define an array or object is of course the literal way, because you don't need to call the constructor first. Anyway, the actual speed difference is negligible, really.

I did a speed test in Chrome 6, in which I defined 20 times 10000000 the same array 1, 2, 3, which gave these results:

Average speed per 10000000 calls
Array Constructor  : 226.55 ms
Array Literal      : 159.1  ms

As you can see, the array literal is 67,45ms faster per 10000000 array definitions.

like image 52
Harmen Avatar answered Oct 05 '22 22:10

Harmen


From a typical programmer perspective, it seems that you tend to use var arr = new Array(); so as to give the feeling of typical object instantiation. But in javascript its usually good practice to use var arr = []; Personally I dont see much difference in using both ways except for one parameter which is explained by Harmen.

Check this link too - http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/

like image 34
Sachin Shanbhag Avatar answered Oct 06 '22 00:10

Sachin Shanbhag