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 sets
let 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 method
console.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, and boolean data 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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources