JS: Set.prototype.forEach

By Xah Lee. Date: . Last updated: .

New in ES2015.

Apply function f to all values in set set_obj in the order the values are inserted.

Does not modify the set object.

Return undefined.

If thisArg is given, it will be used as this value of f. If it is not given, undefined is used.

[see JS: “this” Binding]

The function f is passed 3 arguments, x y z. The x is the current value in the set, y is the same as x, z is the set being iterated. The reason the first two arguments are the same is because to keep compatible in form with the “forEach” method of Array.

[see JS: Array.prototype.forEach]

const s = new Set([3,4,5]);

// apply a function to each value
const t = s.forEach(
    ((x) => {
        console.log(x+10);
        return x+10;
    })
);
// prints
// 13
// 14
// 15

// does not modify the variable
console.log(s); // Set { 3, 4, 5 }

// returns undefined
console.log(t); // undefined

Here's example of 3 args form of f in forEach on a set object.

// 3 args form of f in forEach on a set object

const s = new Set([3,4,5]);

// apply a function to each value
s.forEach( function (e, i, s) {  console.log([e, i, s]); } );

// prints

// [ 3, 3, Set { 3, 4, 5 } ]
// [ 4, 4, Set { 3, 4, 5 } ]
// [ 5, 5, Set { 3, 4, 5 } ]

JS Set

  1. Set Tutorial
  2. Union, Intersection, Difference

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials