Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.
The TypeScript forEach()
method executes a function on each item in an array.
Here's a simple example of the forEach()
method. You can read the rest of the tutorial to learn more.
Example
let nums: number[] = [1, 2, 3, 4];
// Function that prints the number passed to it
function printNumber(arg: number): void {
console.log(arg);
}
// Use forEach() to execute printNumber()
// on each element in the numbers array
nums.forEach(printNumber);
// Output:
// 1
// 2
// 3
// 4
Here, we have used the forEach()
method to execute the printNumber()
function on each element of the nums[] array.
TypeScript forEach()
The syntax of the forEach()
method is:
array.forEach(function(currentValue, index?, arr?))
Here,
function
- A function to be run for each element of an array.currentValue
- The current element of the array.index
- The index of the current element (optional).arr
- The array on which the loop is being performed (optional).
Updating Array Elements
You can use the forEach()
method to update array elements. For example,
let students: string[] = ["John", "Sara", "Jack"];
function addText(item: string, index: number, arr: string[]) {
// Add "Hello" to the array elements
arr[index] = "Hello" + item;
}
// Use forEach() to execute addText()
// on each element of the students array
students.forEach(addText);
console.log(students);
Output
[ 'HelloJohn', 'HelloSara', 'HelloJack' ]
Here, the addText()
function is passed to forEach()
and is executed on each element of the students[]
array.
The function directly modifies the students[] array by adding "Hello"
to each element of the array.
forEach with Arrow Function
You can use an arrow function with the forEach()
method. For example,
let students: string[] = ["John", "Sara", "Jack"];
// Use arrow function with forEach()
students.forEach(element => {
console.log(element);
});
Output
John Sara Jack
In the above example, the forEach()
method is used with an arrow function to iterate through the students[] array.
Here, each element of the students[] array is passed to the arrow function, which then prints the element to the console.
More on forEach()
Unlike traditional loops, you cannot use the continue
statement inside a forEach()
callback.
To skip certain iterations, use conditional statements and return
to exit the current callback early. For example,
let nums: number[] = [1, 2, 3, 4, 5];
// Use forEach() to only print odd numbers
nums.forEach((value: number) => {
// Check if value is even
if (value % 2 === 0) {
return; // Skip iteration
}
// Prints only odd values
console.log(value);
});
Output
1 3 5
Here, the callback function checks if the current array element is even. If it is, the return
statement skips the iteration.
Thus, console.log(value);
is only executed when value
is odd.
You can iterate through elements of a Set
using the forEach()
method. For example,
// Create a set of numbers
let numbersSet: Set<number> = new Set<number>([1, 2, 3]);
function printItems(item: number): void {
console.log(item);
}
// Use forEach() to execute printItems()
// on each element of the numbersSet set
numbersSet.forEach(printItems);
Output
1 2 3
Here, we have used the forEach()
method to call the printItems()
function on each element of the numbersSet set.
You can iterate through Map
elements using the forEach()
method. For example,
// Create a map where the key is of string type
// And the value is of either string or number type
let employeeInfo: Map<string, string | number> = new Map<string, string | number>();
// Insert elements to map
employeeInfo.set("name", "Jack");
employeeInfo.set("age", 27);
function printInfo(value: string | number, key: string) {
console.log(`${key} : ${value}`);
}
// Use forEach() to execute the printInfo() function
// on each items of the employeeInfo map
employeeInfo.forEach(printInfo);
Output
name : Jack age : 27
Use forEach()
when you need to apply a function to each element in an array and prefer a cleaner and more functional programming approach.
Use a for
loop when you need detailed control over the iteration process, such as modifying the loop counter.
Let's look at the example below, where we have used both foreach()
and for
to iterate over an array.
let fruits: string[] = ["apple", "banana", "cherry"];
// Loop using forEach()
console.log("Using forEach():");
fruits.forEach(function(fruit: string): void {
console.log(fruit);
});
// Loop using a for loop
console.log("\nUsing a for loop:");
for (let i: number = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output
Using forEach(): apple banana cherry Using a for loop: apple banana cherry
Also Read: