Yosef Yosef - 2 years ago 104
Javascript Question

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

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download