Sparse Arrays

JavaScript implements arrays as a type of Object. These Array objects have properties that are identified by number rather than name, they have a length property to identify how many numbered properties there are and they have a selection of methods for processing the numbered properties. In all other respects these Array objects operate just the same as any other object.

What this means is that Arrays in JavaScript are sparse in that they can contain holes - not every entry in a JavaScript Array needs to exist. There are three ways that we can quickly create a sparse array in JavaScript to demonstrate this.

a = new Array(6); // length is 6 but there are no entries in the array
b = [,,,,,]; // again length is 6 but there are no entries in the array
a[12] = 1; // now the length is 13 and there is one entry in the array

Note that in these instances the missing entries are not undefined - the missing entries do not exist at all. If we were to create the missing entries with undefined values then we'd have a dense array rather than a sparse one. We can specify that we specifically want to create a dense array where all of the entries exist using the following:

c = Array.apply(null,Array(6));
// length is 6 and there are 6 entries in the array all undefined

When you call any of the JavaScript methods for processing the entries in the array the actual processing performed will differ depending on whether the array is sparse or dense in that the JavaScript Array methods only process those numbered properties that actually exist.

a.forEach(function (x, i) { console.log(i+". "+x) });

Assuming that the above commands are all executed this forEach call will produce exactly one line of output to the log corresponding to the one element that actually exists. The alternative of using a for loop to process the array will result in problems when it tries to process entries that are missing whereas the forEach automatically skips the missing entries completely. The other alternative of using a loop has the problem that any methods that you have added to the array and have not flagged as non-enumerable will also get processed. Since neither of these will necessarily correctly process an array you are best to stick to using the built in array methods for performing this processing.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow