7

In most javascript apps I usually declare an array like so

var x = [];

but I've seen a ton of example code on MDN that take this approach instead

var x = new Array(10);

With V8/other modern JS engines, do you see a real benefit one way or the other?

Toran Billups
  • 27,111
  • 40
  • 155
  • 268

1 Answers1

3

None. Javascript doesn’t implement real arrays. It all gets abstracted through javascript object notation.

So say:

a = [0, 1];
b = {"0": 1, "1": 1};

Has the same effect:

a[0] //0
b[0] //0

One more thing to keep in mind is when you do:

a[100] = 100;

The length gets automagically set to 101. Even though:

a[2] //undefined
beautifulcoder
  • 10,832
  • 3
  • 19
  • 29
  • 1
    I recall somebody demonstrating that some new engines take the size argument on faith and actually do some pre-allocation. It used to be the case that the array size was a *bad* idea, because if *really* old runtimes would blindly preallocate regardless of the value, leading to possible out-of-memory conditions. – Pointy Apr 19 '14 at 21:00
  • It differs memory allocation wise. So it could matter depending on the scenario. – Johan Apr 19 '14 at 21:00