Basic syntax of forEach
in TypeScript
The basic syntax of the forEach
loop in TypeScript is straightforward. Here's an example:
let numbers: number[] = [1, 2, 3, 4, 5]numbers.forEach((value) => {console.log(value)})
In this example, the forEach
method iterates over each element in the numbers
array and logs it to the console.
Using forEach
with index
Sometimes, you may need to access the index of each element during iteration. The forEach
method provides an optional second parameter for this purpose:
let fruits: string[] = ['apple', 'banana', 'cherry']fruits.forEach((fruit, index) => {console.log(`${index}: ${fruit}`)})
In this example, the index of each element is logged along with the element itself.
forEach
vs map
While forEach
and map
may seem similar, they serve different purposes. The forEach
method executes a provided function on each array element but does not return a new array. The map
method, on the other hand, returns a new array with the results of applying a provided function to each element.
Here’s a comparison:
let numbers: number[] = [1, 2, 3, 4, 5]// Using forEachnumbers.forEach((value) => {console.log(value * 2) // No new array is created})// Using maplet doubledNumbers = numbers.map((value) => value * 2)console.log(doubledNumbers) // [2, 4, 6, 8, 10]
forEach
with objects (Record
Type)
In TypeScript, you can use forEach
with arrays of objects or Record
types. Record
types in TypeScript are object types with specified key value pairs.
Here’s an example of a forEach
loop using a Record
object:
type Person = {name: stringage: number}let people: Record<string, Person> = {person1: { name: 'Alice', age: 25 },person2: { name: 'Bob', age: 30 }}Object.keys(people).forEach((key) => {console.log(`${key}: ${people[key].name}, ${people[key].age}`)})
In this example, we iterate over the keys of the people
object and log the details of each person.
Continuing in forEach
Unlike traditional loops, you cannot use continue
within a forEach
loop to skip to the next iteration. Instead, you can use a conditional statement to achieve a similar effect:
let numbers: number[] = [1, 2, 3, 4, 5]numbers.forEach((value) => {if (value % 2 === 0) {return // Skip the even numbers}console.log(value) // Only logs odd numbers})
Error handling in forEach
It is also essential to handle potential errors within a forEach
loop. If an error occurs, it can disrupt the loop’s execution. Using try-catch blocks can help manage this:
let numbers: number[] = [1, 2, 3, 4, 5]numbers.forEach((value) => {try {if (value === 3) {throw new Error('An error occurred!')}console.log(value)} catch (error) {console.error(error.message)}})
Summary
- The basic syntax of
forEach
allows you to execute a function on each array element. - You can access the index of each element using the optional second parameter.
- The
forEach
method differs frommap
in that it does not return a new array. - You can use
forEach
with objects (Record
types) by iterating over the object’s keys. - Using conditional statements can mimic the
continue
behavior in aforEach
loop. - Error handling within
forEach
can be managed using try-catch blocks.
For further reading on using forEach
loops in TypeScript see the official documentation.