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:
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:
// code to be executed
}
Example
First, create a “Set” of string-type values:
Now, iterate the Set to print all the values on the console using the “for-of” loop:
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:
// code to be executed
});
Example
Consider the above Set of languages and iterate it using the “forEach()” method to print the Set elements:
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.