0

One of the advantages I've heard for the use of forEach vs a for/of on an iterable is that you can chain methods together.

As a basic example of the two I have:

let arr = [1,2,3];
arr.forEach((elem, idx) => {
    console.log(elem);
})
for (let elem of arr) {
    console.log(elem);
};

What would be an example of chaining together multiple forEach's?

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

2

forEach returns undefined. You can't call a method on undefined.

The chaining you might have heard about is when forEach is at the end of some processing which returns an array, like after array methods like map,reduce etc:

let arr = [1,2,3];

arr.map(x => x*2).forEach((elem, idx) => {
    console.log(elem);
})
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
1

forEach always returns undefined. forEach is not chain-able like map, reduce or filter.

VCodePro
  • 21
  • 4