DEV Community

Discussion on: JavaScript Arrays: .forEach - The Functional for of loop

Collapse
 
mikegeyser profile image
mike geyser ⟨ 🐘 ⁄ ⟩

Thanks for the great read! It's always interesting seeing other peoples perspectives on it.

I feel like forEach is in this weird space between for of and the more functional operators map/reduce. Almost every use case for looping over an array is to change its shape, either by manipulating each item (which makes map ideal) or by aggregating the array contents (which makes reduce ideal).

Using your key/value map example, I would typically use reduce as follows:

const fruitEmojis = ['🍎', '🍌', '🍍'];
const fruitNames = ['apple', 'banana', 'pineapple'];

let fruitMap = fruitEmojis.reduce(function(map, currentFruitEmoji, index) {
  const key = fruitNames[index];
  map[key] = currentFruitEmoji;

  return map;
}, {});

console.log(fruitMap);

It's very similar, but has notably fewer side effects. You can also make it really terse, if that's your kind of thing, and if you use the spread operator to shallow copy you can reduce the footprint for unintentional side effects even further:

let fruitMap = fruitEmojis.reduce((map, current, i) => ({ 
    ...map, 
    [fruitNames[i]]: current 
}), {});

Just some thoughts. :)

Collapse
 
cedpoilly profile image
Cedric

Thanks for this insightful explanation @mikegeyser !

It's true that if I'm using .forEach quite often, it's worth considering using more "specialised" methods such as .reduce.

Which is a great transition to announce the topic for the next article of this series: Array.prototype.reduce!

Stay tuned! ✌