loading...

re: Sets in ES6 - A Quick Guide VIEW POST

FULL DISCUSSION
 

The third value is the current Set you're iterating over. A number of methods have this argument, and I've never figured out why

This allows you to reuse the callback in several places, without losing the flexibility you have, when defining the callback inline. From a callback that is defined somewhere else, you will loose the ability to look at the object you are currently working.
Use case: transform an array of values to an srray of strings, that have the form `${value} of ${array.length} items`.
Without the third parameter, you'd need to write a higher order function that takes the length (or the array itself) returns a function that can be used as a callback function:

const createCallback = array => (index, value) => (
value + " of " + array.length + " items"
);
const inputArray = ["foo", "bar"];
console.log(inputArray.map(createCallback(inputArray)));

Code like this is something what I call an "eyebrow raiser". What happens if someone changes the createCallback function and mutates the array there (think of the poor guy, who has to debug that... )? You need to take care to have tests in place that protect the code from this kind of change (super edgy edge case that is super dangerous at the same time).

 

More than that! You need it if you chain methods like so:

myArr
  .filter(val => !!val)
  .forEach((val, idx, filteredArr) => {
    // now has access to the filtered array via `filteredArr`
  })
  .map((val, idx, filteredArr) => {

  })
  .forEach((val, idx, mappedArr) => {
    // now has access to the filtered and mapped array via `mappedArr`
  });

Otherwise, you'd have to execute and assign these to variables and reach out of the inner scope of the call back function.

code of conduct - report abuse