addyosmani / es6-equivalents-in-es5

WIP - ES6 Equivalents In ES5

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

filter vs forEach

gaboesquivel opened this issue · comments

Is there a reason to prefer forEach over filter ?

var fives = [];
var nums = [1, 2, 5, 15, 25, 32];
nums.forEach(v => {
  if (v % 5 === 0)
    fives.push(v);
});

over

var nums = [1, 2, 5, 15, 25, 32];
var fives = nums.filter(v => v % 5 === 0 )

@gaboesquivel - good eye here. Both examples are essentially doing the same thing, but the main differences I see with the two examples are:

  • forEach is being used a side effect function (since it doesn't actually return anything), so we have to create an outer variable to store our results
  • filter does actually return something (the transformed array) so we can just save the results of filter directly to the fives variable.

imo, filter is more appropriate b/c you generally want to avoid side-effects.

Just realized that's intended to be an difference between statement bodies. Filter is an expression since it returns a value, just as map in the example lines above.