🔰iterating elements
JS ⟩ object ⟩ built-in ⟩ Array ⟩ iterating arrays
// ⭐️ for-of: treats "holes" as undefined
for (const value of array) {}
for (const [index, value] of array.entries()) {} // with index
// ⭐️ forEach: ignores "holes"
arr.forEach(value => ...) // .forEach() methodUnlike the for-of loop, forEach() is aware of sparse arrays and does not invoke the function for nonexistent elements.
iterating arrays
for-of loop
arr.forEach() method
let a = []; // sparse array
a[1] = 'hi';
a[5] = 'world';
let forofCount = 0;
let foreachCount = 0;
// ⭐️ for-of: treats "holes" as `undefined`.
for (const value of a) {
forofCount += 1;
console.log(forofCount, value);
}
// 1 undefined, 2 'hi', 3 undefined, ... 6 'world'
// ⭐️ forEach: ignores "holes".
a.forEach(value => {
foreachCount += 1;
console.log(foreachCount, value);
})
// 1 'hi', 2 'world'Last updated
Was this helpful?