Open In App

What is a Sparse Array in JavaScript ?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A sparse array is an array in which not all elements have been assigned a value. This means that there are “holes” or undefined slots in the array where no value is explicitly set.

Example: Here, the array sparseArray has a length of 4, but only two elements have values ('one' at index 1 and 'three' at index 3). The slots at index 0 and 2 are undefined, creating a sparse array.

Javascript




let sparseArray = [];
sparseArray[1] = 'one';
sparseArray[3] = 'three';
 
console.log(sparseArray); // Output: [ , 'one', , 'three']
console.log(sparseArray.length); // Output: 4


Output

[ <1 empty item>, 'one', <1 empty item>, 'three' ]
4


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads