The forEach() method executes a provided function once for each array element. It does not return a value.
The syntax of Array.forEach() method is:
forEach(callbackfn: function, thisArg?: any): void
This forEach() method of Array performs the specified action for each element in an array.
Parameter | Optional/Required | Description |
---|---|---|
callbackfn | required | A function to execute for each element, taking three arguments: the current element, the index of the current element, and the array being traversed. |
thisArg | optional | Value to use as this when executing callbackfn. |
Array.forEach() returns value of type void
.
The forEach() method can be used to iterate over each element of an array and perform a specified action.
For example,
arr
with numeric values [1, 2, 3, 4, 5].forEach(callbackfn)
to execute the callback function for each element in the array.const arr = [1, 2, 3, 4, 5];
arr.forEach(element => console.log(element));
1 2 3 4 5
The forEach() method can be used to modify each element in an array.
For example,
arr
with numeric values [1, 2, 3, 4, 5].forEach(callbackfn)
to execute the callback function for each element in the array.const arr = [1, 2, 3, 4, 5];
arr.forEach(element => console.log(element * 2));
2 4 6 8 10
The forEach() method can be used with a callback function that takes the current element, index, and array as parameters.
For example,
arr
with string values ['a', 'b', 'c'].forEach(callbackfn)
to execute the callback function for each element in the array.const arr = ['a', 'b', 'c'];
arr.forEach((element, index) => console.log(`Element: ${element}, Index: ${index}`));
Element: a, Index: 0 Element: b, Index: 1 Element: c, Index: 2
In this TypeScript tutorial, we learned about forEach() method of Array: the syntax and few working examples with output and detailed explanation for each example.