I like Array.forEach() and use it whenever I need to iterate through elements. However one needs to be aware of its quirk.
const arr = new Array(5);
arr[0] = 0;
arr[4] = 4;
A typical for outputs all elements including those not initialized yet (hold your breath for a moment on the initialized thing).
for (let i = 0; i < arr.length; i++) console.log("for rocks", arr[i]);
/* output
for rocks 0
for rocks undefined
for rocks undefined
for rocks undefined
for rocks 4
*/
Now, repeat the same for forEach.
arr.forEach(ele => console.log("forEach rocks too"));
/* output
forEach rocks too
forEach rocks too
*/
Hmm.. that is strange.
Let’s use a fill with array but not assign any value.
const arr = new Array(5).fill();
arr[0] = 0;
arr[4] = 4;
for (let i = 0; i < arr.length; i++) console.log("for rocks", arr[i]);
arr.forEach(ele => console.log("forEach rocks too"));
/*
for rocks 0
for rocks undefined
for rocks undefined
for rocks undefined
for rocks 4
forEach rocks too
forEach rocks too
forEach rocks too
forEach rocks too
forEach rocks too
*/
What is this black magic?
I am flabbergasted. Is forEach right for me?
Yes.
forEach is pretty, smart and committed (to the future of Javascript). You can both live a happy life.
A better question to think about is why we initialize empty arrays like crazy.