JavaScript: 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 Array.prototype.length] )

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

It doesn't exist, therefore has no value.

Note, it is different from having values of undefined .

If you access non-existent index, JavaScript return undefined .

Remember, array indexes are Property Keys of non-negative integers, all are string type.

How to Check Missing Keys?

// use Object.keys to see existing indexes
const xx = [3, 4, 5];
delete xx[1];
console.log(Object.keys(xx)); // [ "0", "2" ]
// use hasOwnProperty to check if a index exist
const xx = [3, 4, 5];
delete xx[1];
console.log(xx.hasOwnProperty("1") === false);

How to create a sparse array?

Sparse array is created when you call Array(n), where n is a positive integer. [see Array Constructor]

Array becomes sparse when you use Delete operator to delete a element.

// using delete operator results a sparse array

const xx = ["a", "b"];
delete xx[0];
console.log(xx.length === 2);
console.log(xx.hasOwnProperty("0") === false);

Array becomes sparse when you set array property length to a number bigger than the index of last item.

Array becomes sparse when a new element is added with index greater than 1 from the last item's index. For example: const xx=["a","b"]; xx[9]="z";

// Example of a sparse array, by adding a item with index greater than length
const xx = ["a", "b"];

console.log(xx.length === 2);

xx[9] = "xyz";
// now xx is sparse array

console.log(xx.length === 10);
console.log(xx.hasOwnProperty("3") === false);

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 Object or Set Object .

JavaScript Array
JavaScript in Depth

JavaScript in Depth

Basic Syntax
Value Types
Object and Inheritance
Iterable 🌟