-1

Suppose we have 3 arrays:

var arr1 = [undefined, undefined, undefined];
var arr2 = [, , ,];
var arr3 = new Array(3);

Are all of them identical in JavaScript? If we wants to use undefined as default value for fixed size array, can we use them interchangeably?

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
  • @Pointy I've seen it right before your comment.. stupid me.. – Mihai Matei May 04 '16 at 14:38
  • 1
    @MateiMihai it's a difference, but for many purposes it doesn't matter. Really in practice I always just use `[]` for an empty array. Relying on the array length seems like a really fragile design pattern. – Pointy May 04 '16 at 14:40

1 Answers1

5

The second two are the same (though the second one might cause issues on some browsers), but the first is different.

The first one

var arr1 = [undefined, undefined, undefined];

makes explicit assignments to the first three indexes in the array. Even though you're assigning undefined, the fact that indexes 0, 1, and 2 are targets of assignment operations means that those elements of the array will be treated as "real" by methods like .reduce():

[undefined, undefined, undefined].reduce(function(c) { return c + 1; }, 0);
// 3

[,,].reduce(function(c) { return c + 1; }, 0);
// 0

Many of the Array.prototype methods skip uninitialized array elements.

Pointy
  • 405,095
  • 59
  • 585
  • 614