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