What is set.forEach() method in TypeScript?
Overview
In TypeScript, we can use the forEach() method to loop or iterate over set entries. A Set is a data structure that contains unique entries without duplicates.
Syntax
theSet.forEach(value =>{// loop entries one by one})
Syntax for set.forEach()
Parameters
value: This represents the value of each entry of a set.
Return value
This method returns a loop that allows us to iterate over each entry of the set.
Code example
Let's look at the code below:
// create some setslet names = new Set<string>(["Theodore", "David", "John", "Janme"])let evenNumbers = new Set<number>([2, 4, 6, 8, 10, 12])let booleanValues = new Set<boolean>([true, false])// use the forEach methodconsole.log("The entries of the set 'names' are:")names.forEach(value =>{console.log(value)})console.log("\nThe entries of the set 'evenNumbers' are:")evenNumbers.forEach(value =>{console.log(value)})console.log("\nThe entries of the set 'booleanValues' are:")booleanValues.forEach(value =>{console.log(value)})
Code explanation
- Lines 2 to 4: We create some sets of
string,number, andbooleandata types. - Lines 7, 12, and 17: We use the
forEach()method to loop through the sets. And then, we print each entry of the set to the console.