JavaScript: sparse arrays vs. dense arrays

In general, arrays in JavaScript are sparse – they can have holes in them, because an array is simply a map from indices to values. This blog post explains how to create dense arrays, arrays without holes.

Sparse arrays

Creating a sparse array of a given length is simple:

> var a = new Array(3);
> a
[ , , ]
> a.length
3
> a[0]
undefined

When you iterate over it, you can see that it has no elements. JavaScript skips the holes.