Today I Learned - Rocky Kev

TIL Sparse Arrays

POSTED ON:

TAGS:

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:

TIL Sparse Arrays

The ['Batman', , 'Bane'] array is a sparse array. See how it there is a blank?

TIL checking falsy values inside an array

Using the key Boolean to find any true/false statements inside an array

TIL about flattening a JS array