Typescript

How to Loop Over a Set in TypeScript?

Set” is a predefined data structure in TypeScript, which stores a set/collection of unique values. The set’s value may consist of any data type including strings, numbers, or objects. One of the key features of a set is that it excludes duplicate values. In order to iterate over the values in a set, several approaches are available in TypeScript, including a for-of loop, or the forEach() method.

This post will describe the way to loop over the Set in TypeScript.

How to Loop Over a Set in TypeScript?

To iterate or loop over a Set in TypeScript, use the following approaches:

Before moving ahead, first understand that for executing a TypeScript file, it must be transpile into a JavaScript file after every modification and then run the JavaScript code on the terminal using the given commands:

tsc dictionary.ts
node dictionary.js

Method 1: Loop Over a Set in TypeScript Using “for-of” Loop

For looping or iterating the “Set” in TypeScript, use the “for-of” loop. The “for-of” loop is a JavaScript feature that allows iterating over the elements of an iterable, such as a set.

Syntax

The following syntax is utilized for the “for-of” loop:

for (const value of iterable) {
 // code to be executed
}

Example

First, create a “Set” of string-type values:

const langSet = new Set<string>(['HTML', 'CSS', 'JavaScript', 'jQuery']);

Now, iterate the Set to print all the values on the console using the “for-of” loop:

for(var elem of langSet){
 console.log(elem);
}

Output

Method 2: Loop Over a Set in TypeScript Using “forEach()” Method

Another way to loop over the Set in Typescript is to use the “forEach()” method. It is a built-in method of the Set object that allows the execution of a provided function once for every element in a Set.

Syntax

Follow the given syntax for iterating the Set using the “forEach()” method:

mySet.forEach((callbackFunc) => {
 // code to be executed
});

Example

Consider the above Set of languages and iterate it using the “forEach()” method to print the Set elements:

langSet.forEach(elem => {
 console.log(elem);
});

Output

That’s all about the loop over a Set in TypeScript.

Conclusion

To loop or iterate over a Set in TypeScript, use the “for-of” loop or the “forEach()” method. Both approaches have their own advantages and disadvantages, and the choice of which to use may depend on the specific use case. The common and best-used approach is the “forEach()” method. This post described the way to loop over the Set in TypeScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.