TypeScript forEach loops

Kenny DuMez
Kenny DuMez
Graphite software engineer

The basic syntax of the forEach loop in TypeScript is straightforward. Here's an example:

Terminal
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.

Sometimes, you may need to access the index of each element during iteration. The forEach method provides an optional second parameter for this purpose:

Terminal
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.

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:

Terminal
let numbers: number[] = [1, 2, 3, 4, 5]
// Using forEach
numbers.forEach((value) => {
console.log(value * 2) // No new array is created
})
// Using map
let doubledNumbers = numbers.map((value) => value * 2)
console.log(doubledNumbers) // [2, 4, 6, 8, 10]

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:

Terminal
type Person = {
name: string
age: 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.

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:

Terminal
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
})

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:

Terminal
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)
}
})
  • 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 from map 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 a forEach 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.

Stay unblocked. Ship faster.
Experience the new developer workflow - create, review, and merge code continuously. Get started with one command.
Get started

Give your PR workflow
an upgrade today

Stack easier | Ship smaller | Review quicker

Or install our CLI.
Product Screenshot 1
Product Screenshot 2