Skip to content

Using forEach() to Loop Through an Array in TypeScript

TypeScript, Programming, JavaScript1 min read

When working with arrays in TypeScript, you often need to iterate through their elements to perform various operations. One of the most reliable and straightforward methods for accomplishing this task is by using the forEach() method. In this article, we will dive into the usage of forEach() to loop through arrays in TypeScript, providing clear examples to illustrate its practical application.

Understanding the forEach() Method

The forEach() method is an essential feature of JavaScript and TypeScript arrays, allowing you to execute a provided function once for each array element. With its intuitive syntax, it offers a cleaner alternative to traditional for loops, making your code more readable and concise. The forEach() method iterates over an array and calls a provided callback function for each element, passing the current element, its index, and the entire array as arguments.

1const numbers: number[] = [1, 2, 3, 4, 5];
3numbers.forEach((number, index) => {
4 console.log(`Element at index ${index} is: ${number}`);

In this example, the forEach() method is used to iterate through the numbers array, logging each element along with its respective index to the console. It's worth noting that the forEach() method does not return a new array and simply performs an action on each element.

Practical Examples

Modifying Array Elements

Using forEach() allows for easy modification of array elements without the need for explicit indexing. Let's consider a scenario where we want to double each number in an array:

1let originalNumbers: number[] = [1, 2, 3, 4, 5];
2let doubledNumbers: number[] = [];
4originalNumbers.forEach(number => {
5 doubledNumbers.push(number * 2);
8console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

In this instance, we utilize the forEach() method to iterate through originalNumbers, doubling each element and pushing it to the doubledNumbers array.

Working with Objects

When dealing with arrays of objects, forEach() remains a powerful tool. Consider the following example, where we have an array of user objects and want to print out each user's name:

1interface User {
2 name: string;
3 age: number;
6const users: User[] = [
7 { name: "Alice", age: 25 },
8 { name: "Bob", age: 30 }
11users.forEach(user => {
12 console.log(`User: ${}, Age: ${user.age}`);

Here, the forEach() method enables us to easily access and work with each object within the users array, simplifying our iteration process.

In TypeScript, the forEach() method provides an elegant and efficient way to iterate through arrays, offering simplicity and readability when working with array elements. By leveraging its capabilities, you can streamline your code and enhance its maintainability. Whether you're modifying array elements or working with complex object structures, forEach() proves to be a valuable asset in your development arsenal.