Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript

What is set.forEach() method in TypeScript?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
})
Using forEach() method to print all enteries

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.

RELATED TAGS

typescript

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring