Why does Array.apply(null, [args]) act inconsistently when dealing with sparse arrays?

new Array(3) […] can also be rewritten as [undefined, undefined, undefined]

No – as you just have seen, the array constructor creates sparse arrays so it should be rewritten as [,,,].

If the final term of of sparseArr is undefined

Nope. You’re forgetting about trailing commata, which are optional since EcmaScript 5. Actually [1] is just equivalent to [1,] (both have a length of 1).

To get sparse “slots”, you will have to add additional commata:

[] // empty array
[,] // empty array
[,,] // [undefined x 1]
[,,,] // [undefined x 2]

If sparseArr contains only a single term, the resulting denseArr equals [undefined x N]

Consider what it means to call the apply method:

Array.apply(null, [3,,4,1]) ≡ Array(3, undefined, 4, 1)
Array.apply(null, [3,4]) ≡ Array(3, 4)
Array.apply(null, [1]) ≡ Array(1)

And you know what the Array constructor does when being called with a single numeric arguments – it creates a sparse array of that length…

Leave a Comment