-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?

2
  • @Pointy I've seen it right before your comment.. stupid me.. Commented May 4, 2016 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. Commented May 4, 2016 at 14:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.