How to Get Index in forEach Loop in TypeScript?

Recently, in an online webinar, someone asked about getting the index in a forEach loop in TypeScript. In this tutorial, I will explain how to get the index in a forEach loop in TypeScript. I will also show you some practical examples.

What is the forEach Loop in TypeScript?

The forEach loop in TypeScript is a method that allows you to execute a provided function once for each array element. It’s a straightforward and readable way to iterate over array elements without the need for a traditional for loop.

Basic Syntax of forEach Loop

The basic syntax of the forEach loop in TypeScript is as follows:

array.forEach((element, index) => {
  // Your code here
});

In this syntax:

  • element refers to the current element being processed in the array.
  • index is the optional second parameter that represents the index of the current element.

Read How to Use TypeScript Loops to Execute Code Multiple Times?

How to Access the Index in TypeScript forEach Loop

To access the index of each element during iteration, you simply include the second parameter in the callback function. Let me show you an example:

Example: Logging Names with Indices

Let’s say we have an array of city names from the USA, and we want to log each city name along with its index.

const cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];

cities.forEach((city, index) => {
  console.log(`City at index ${index} is ${city}`);
});

In this example:

  • cities is the array we are iterating over.
  • city is the current element (city name) in the array.
  • index is the index of the current element.

When you run this code, it will output:

City at index 0 is New York
City at index 1 is Los Angeles
City at index 2 is Chicago
City at index 3 is Houston
City at index 4 is Phoenix

Here is the exact output in the screenshot below:

Access the Index in TypeScript forEach Loop

Now, let me show you some practical use cases.

Read For Loop Range in TypeScript

Update Elements Based on Index

You might want to update elements in an array based on their index. For instance, if you need to append the index to each city name:

const updatedCities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];

updatedCities.forEach((city, index, array) => {
  array[index] = `${city} (${index})`;
});

console.log(updatedCities);

This will modify the updatedCities array to:

["New York (0)", "Los Angeles (1)", "Chicago (2)", "Houston (3)", "Phoenix (4)"]

Conditional Operations

Sometimes, you may need to perform operations only on specific elements based on their index. For example, logging only the cities at even indices:

const cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];

cities.forEach((city, index) => {
  if (index % 2 === 0) {
    console.log(`City at even index ${index} is ${city}`);
  }
});

This will output:

City at even index 0 is New York
City at even index 2 is Chicago
City at even index 4 is Phoenix

Conclusion

Using the forEach loop in TypeScript is an efficient way to iterate over array elements. By including the optional second parameter, you can easily access the index of each element, enabling a wide range of operations from logging to conditional updates. In this tutorial, I explained how to get the index in forEach loop in TypeScript.

You may also like: