.forEach()

The method is used to iterate over the elements of a Set collection.

Time to read: less than 5 min

Briefly

The forEach() method is used to iterate over the elements of a Set. Iteration occurs in the order of adding values to the collection from oldest to newest.

The method works identically to the similarly named array method.

Example

        
          
          const watchList = new Set(['The Shining', 'Interstellar', 'Casino'])watchList.forEach(function(value) {  console.log(`Need to watch «${value}»`)})// Need to watch «The Shining»// Need to watch «Interstellar»// Need to watch «Casino»
          const watchList = new Set(['The Shining', 'Interstellar', 'Casino'])
watchList.forEach(function(value) {
  console.log(`Need to watch «${value}»`)
})

// Need to watch «The Shining»
// Need to watch «Interstellar»
// Need to watch «Casino»

        
        
          
        
      

How it is written

The method takes two arguments:

1️⃣ A callback function to be executed on each element of the collection. The function can use up to three parameters, which can be omitted if not needed:

  • current value;
  • current value (the index is in the second position in the array, but Set is an unindexed collection. For compatibility, it was decided to return the value twice);
  • the collection being iterated.

2️⃣ A value to be used as this inside the function.

Using all parameters looks like this:

        
          
          const watchList = new Set(['The Shining', 'Interstellar', 'Casino'])watchList.forEach(function(value, value2, s) {  console.log(`${this.name}, need to watch «${value}»`)}, {name: 'Evgen'})// Evgen, need to watch «The Shining»// Evgen, need to watch «Interstellar»// Evgen, need to watch «Casino»
          const watchList = new Set(['The Shining', 'Interstellar', 'Casino'])
watchList.forEach(function(value, value2, s) {
  console.log(`${this.name}, need to watch «${value}»`)
}, {name: 'Evgen'})

// Evgen, need to watch «The Shining»
// Evgen, need to watch «Interstellar»
// Evgen, need to watch «Casino»

        
        
          
        
      

Such notation is rarely used; the preference is given to the short notation described in the initial example.