JavaScript Set forEach() Method Tutorial

In this section, we will learn what the Set forEach() method is and how to use it in JavaScript.

What is JavaScript Set forEach() Method?

We use the `forEach()` method when we want to run a set of instructions for every element of a `Set` object.

JavaScript Set forEach() Method Syntax:

forEach(callback);

forEach() Function Parameters:

The method takes one argument and that is a reference to a function.

This reference function will be called for each element of the target Set object.

The body of this reference function is the place where we can define the instructions we want to be executed per each element of a Set object.

When the `forEach()` method calls our function, it will pass 3 arguments to the function:

  • The first argument is the `value` of each element in the target `Set` object.

Note: the first time the `forEach()` method runs, it will pass the first value of the target `Set` object, the second time it runs, it will pass the second value and so on until the end of the map.

  • The second argument is the copy of the first argument.

Note: the `forEach` method is used in `Map` and `Array` objects as well. In those objects, the first and the second arguments are `keys` and `values` respectively. So making this method behave similarly in the `Set` object as well, the committee used the same structure except the first and the second arguments are values. This is basically for creating a consistent API.

  • The third argument is the reference to the `Set` object in which we’re running the `forEach()` method on it.

forEach() Function Return Value:

The return value of this method is undefined.

Example: using Set forEach() method in JavaScript

const collect = new Set();
 collect.add("Jack");
 collect.add("Jack");
 collect.add("Omid");
 collect.add("John");
 collect.add(100);
 collect.add(200);

 function iterate(value, key, mySet){
     console.log(`The current key is: ${key} and the current value is: ${value}`);
     mySet.delete(value);
   } 
   collect.forEach(iterate);

   console.log(`The size of the 'Set' object is: ${collect.size}`);

Output:

The current key is: Jack and the current value is: Jack

The current key is: Omid and the current value is: Omid

The current key is: John and the current value is: John

The current key is: 100 and the current value is: 100

The current key is: 200 and the current value is: 200

The size of the 'Set' object is: 0

Inside the body of the `iterate` function, we’ve used the third argument, which is the target `Set` object, and deleted the incoming values that are in that `Set` object.

So when the last statement executes to get the size of the collection, we can see that the result value is 0.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies