How to Use the TypeScript forEach Method on Arrays?

In this tutorial, I will explain how to use the TypeScript forEach method to iterate over arrays. The forEach method in TypeScript allows you to execute a provided function once for each element in an array.

What is the TypeScript forEach Method?

The forEach method is an array iteration method in TypeScript that calls a provided callback function once for each element in an array, in ascending index order. It provides a convenient way to loop through an array and perform a specific action on each element.

The syntax for using the forEach method is as follows:

array.forEach(callback[, thisObject]);

Here, callback is the function to be executed for each element in the array, and thisObject (optional) is the value to be used as this when executing the callback.

Check out How to Calculate the Sum of an Array in TypeScript?

Using the forEach Method in TypeScript

Let me show you a practical example to demonstrate how to use the forEach method in TypeScript. Suppose we have an array of objects representing employees in a company based in the USA:

interface Employee {
  name: string;
  age: number;
  position: string;
}

const employees: Employee[] = [
  { name: "John Smith", age: 35, position: "Manager" },
  { name: "Emily Johnson", age: 28, position: "Developer" },
  { name: "Michael Brown", age: 42, position: "Sales Representative" }
];

Now, let’s say we want to print the name and position of each employee. We can achieve this using the forEach method:

employees.forEach((employee) => {
  console.log(`Name: ${employee.name}, Position: ${employee.position}`);
});

Output:

Name: John Smith, Position: Manager
Name: Emily Johnson, Position: Developer
Name: Michael Brown, Position: Sales Representative

In this example, the forEach method iterates over each element (employee) in the employees array and executes the provided arrow function. The arrow function takes each employee object as a parameter and logs their name and position to the console.

Here is the exact output in the screenshot below:

python remove unicode characters

Read How to Reverse an Array in TypeScript?

Using the Index in forEach

Sometimes, you may need to access the index of each element while iterating over an array using forEach. TypeScript allows you to do this by providing an optional second parameter to the callback function, which represents the index.

Let’s consider an example where we have an array of sales figures for each quarter:

const salesFigures: number[] = [10000, 15000, 12000, 18000];

To print the sales figure along with its corresponding quarter, you can use the index in the forEach method:

salesFigures.forEach((figure, index) => {
  const quarter = index + 1;
  console.log(`Quarter ${quarter}: $${figure}`);
});

Output:

Quarter 1: $10000
Quarter 2: $15000
Quarter 3: $12000
Quarter 4: $18000

Here, the forEach method provides the index as the second parameter to the callback function. We use the index to calculate the quarter number (index + 1) and log it along with the corresponding sales figure.
Check out How to Remove an Item from an Array in TypeScript?

forEach vs Other Iteration Methods

While the forEach method is a convenient way to iterate over arrays in TypeScript, it’s worth noting that there are other iteration methods available, such as for loops, for...of loops, and the map method.

The choice of iteration method depends on your specific requirements. Here are a few considerations:

  • If you simply need to iterate over an array and perform an action on each element without creating a new array, forEach is a suitable choice.
  • If you need to create a new array based on the elements of an existing array, the map method is more appropriate.
  • If you need to iterate over an array and have more control over the iteration process, such as the ability to break out of the loop or use the continue statement, a traditional for loop or for...of loop might be more suitable.

It’s important to choose the iteration method that best fits your specific use case and results in clean, readable, and maintainable code.

Best Practices and Tips

When using the forEach method in TypeScript, keep the following best practices and tips in mind:

  1. Use meaningful names for the callback function parameters to enhance code readability.
  2. Keep the callback function concise and focused on a single task to maintain code clarity.
  3. If you need to perform complex operations or multiple actions on each element, consider extracting the logic into a separate function.
  4. Be cautious when modifying the array inside the forEach callback, as it may lead to unexpected behavior. If you need to modify the array, consider using a different iteration method or creating a new array.
  5. Remember that the forEach method does not return a new array. If you need to create a new array based on the elements, use the map method instead.

Conclusion

The TypeScript forEach method provides a convenient and efficient way to iterate over arrays and perform actions on each element. By understanding its syntax, usage with index, and best practices, you can use the power of forEach in your TypeScript projects.

In this tutorial, I explained how to use TypeScript forEach method on arrays?

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.