Last updated 1 year ago
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() method
Unlike 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
for-of vs. forEach
for-of vs. forEach.
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'
JS.info ⟩ iterables
JavaScript: The Definitive Guide ⟩ 7.6 Iterating Arrays