JS: Set.prototype.forEach

By Xah Lee. Date: . Last updated: .

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 } ]

Reference

ECMAScript 2015 §Keyed Collection#sec-set.prototype.foreach

Set Topic

  1. JS: the Set Object Tutorial
  2. JS: Set Union, Intersection, Difference
  3. JS: Set Object
  4. JS: Set.prototype
  5. JS: Set.prototype.forEach
Like what you read? Buy JavaScript in Depth