JavaScript Set Iterating Sets

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

You can use a simple for-of loop to iterate a Set:

const mySet = new Set([1, 2, 3]);

for (const value of mySet) {
  console.log(value); // logs 1, 2 and 3
}

When iterating over a set, it will always return values in the order they were first added to the set. For example:

const set = new Set([4, 5, 6])
set.add(10)
set.add(5) //5 already exists in the set
Array.from(set) //[4, 5, 6, 10]

There's also a .forEach() method, similar to Array.prototype.forEach(). It has two parameters, callback, which will be executed for each element, and optional thisArg, which will be used as this when executing callback.

callback has three arguments. The first two arguments are both the current element of Set (for consistency with Array.prototype.forEach() and Map.prototype.forEach()) and the third argument is the Set itself.

mySet.forEach((value, value2, set) => console.log(value)); // logs 1, 2 and 3


Got any JavaScript Question?