In JavaScript, an array hole (also called a sparse element) means that an index exists in the array but has no value assigned. For example:
// eslint-disable-next-line no-sparse-arrays
const arr = [1, , 3] // index 1 is a holeDifferent iteration methods treat holes differently:
for...of #
Example:
// eslint-disable-next-line no-sparse-arrays
for (const x of [1, , 3]) {
console.log(x) // 1, undefined, 3
}Array methods like forEach, map, reduce #
// eslint-disable-next-line no-sparse-arrays
[1, , 3].forEach(x => console.log(x)) // 1, 3
// eslint-disable-next-line no-sparse-arrays
console.log([1, , 3].map(x => x)); // [1, <1 empty item>, 3
// eslint-disable-next-line no-sparse-arrays
[1, , 3].reduce((acc, cur) => acc.concat(cur), []) // [1, 3]for...in #
// eslint-disable-next-line no-sparse-arrays
for (const x in [1, , 3]) {
console.log(x) // 0, 2
}Summary #
Base on the examples above, we can summarize the following points:
for...ofiterates over the values of the array, including holes.- Array methods like
forEach,reduceiterate over the values of the array, excluding holes. Andmapiterates over the values of the array, including holes. for...initerates over the indices of the array, excluding holes.