What is a Sparse Array in JavaScript ?
Last Updated :
31 Jan, 2024
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);
console.log(sparseArray.length);
|
Output
[ <1 empty item>, 'one', <1 empty item>, 'three' ]
4
Share your thoughts in the comments
Please Login to comment...