JS: Sparse Array

By Xah Lee. Date: . Last updated: .

What is a sparse array?

When a array's numerical property key does not exist for index in the range from 0 to n-1 (where n is the value of the property length.)

[see JS: Array.prototype.length]

What is the value of missing elements in a sparse array?

It doesn't exist, therefore has no value.

If you access it (for example, myarray[3] where property key "3" doesn't exist), it has a value of undefined.

Remember, array indexes are property keys of "0" and positive integer, all are string type.

[see JS: Property Key]

What is the effect of sparse array?

When array is sufficiently sparse (missing lots indexes), it loses its special efficiency when accessing array by indexes. In performance, it effectively is like a hashtable.

How to create a sparse array?

In general, you should never use sparse array. Just use a object if necessary. Or, use Map object. [see JS: the Map Object Tutorial]

Array can become sparse in a number of ways.

Do not do any of the above. To add or remove elements, use array methods.

What is the use of sparse array?

Generally, there's no use. Whenever you think spare array is useful, just use a object, or use Map and Set. See:

Example of Sparse Array

// delete operator results a sparse array

// using delete to remove last item
const rr = ["a", "b"];
delete rr[1];

console.log(rr.length); // 2

console.log(rr); // [ 'a', <1 empty item> ]
// Example of a sparse array, by adding a item with index greater than 1 than the last item's index.
const cc = [];
cc[2] = "b"; // now cc is sparse array

console.log(cc); // [ <2 empty items>, 'b' ]
console.log(cc[0]); // undefined
console.log(cc[1]); // undefined
console.log(cc[2]); // b
console.log(cc.length); // 3

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials