TIL Sparse Arrays
POSTED ON:
TAGS: array javascript
Today I learned about Sparse arrays via Sparse vs Dense Arrays in JavaScript
The ['Batman', , 'Bane']
array is a sparse array. See how it there is a blank?
We'll call it 'a hole'.
If you access the value of a hole — names[1] — it evaluates to undefined
.
A problem of the sparse arrays is that many array built-in methods just skip the holes in a sparse array.
For example, `array.forEach(eachFunc)`` doesn’t not invoke eachFunc on the holes:
const names = ['Batman', , 'Bane'];
names.forEach(name => {
console.log(name);
});
// logs 'Batman'
// logs 'Bane'
Same way array.map(mapperFunc), array.filter(predicateFunc), and more functions do skip the holes. If you’ve accidentally created a sparse array, you might find a hard time understanding why an array method doesn’t work as expected.
Related TILs
Tagged: array