JavaScript: 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.

Returns undefined.

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

〔►see JavaScript: “this” Binding

The function f is passed 3 arguments, x y z. 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 JavaScript: Array.prototype.forEach

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

// apply a function to each value
var t = s.forEach( function (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

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

Here's the same thing, using ES2015 features.

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

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

// apply a function to each value
s.forEach( ((...args) => console.log(args)));

// 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. JavaScript: the Set Object Tutorial
  2. JavaScript: Set Union, Intersection, Difference
  3. JavaScript: Set Object
  4. JavaScript: Set.prototype
  5. JavaScript: Set.prototype.forEach
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.