Iterate over a Set in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 15, 2022

banner

Photo from Unsplash

Iterate over a Set in TypeScript #

Use the forEach() method to iterate over a Set in TypeScript. The forEach method takes a function that gets invoked once for each value in the Set object. The forEach method returns undefined.

index.ts
const set1: Set<string> = new Set(['a', 'b', 'c', 'd']); set1.forEach((element) => { // 👇️ a, b, c, d console.log(element); });

We used the Set.forEach method to iterate over the Set.

The function we passed to the method gets called with 3 arguments:

  • the element value
  • the element key
  • the Set object
Note that there are no keys in a Set object and the value is added to be consistent with the forEach methods of Map objects and arrays.

The callback function gets invoked once for each element in the Set, even if it has a value of undefined.

However, the function doesn't get invoked for values that have already been deleted from the Set.

An alternative approach is to use a for...of loop.

index.ts
const set1: Set<string> = new Set(['a', 'b', 'c', 'd']); for (const element of set1) { // 👇️ a, b, c, d console.log(element); }

The for...of loop allows us to iterate over iterable objects like Sets, arrays and Maps.

The loop assigns a variable that stores the current Set element on each iteration.

You should use the for...of loop when you need to use the break keyword to exit the loop, as this is not supported when using the forEach() method.

The for...of loop iterates only over an object's own properties, as opposed to the for...in loop which also iterates over inherited properties.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.