TypeScript Array forEach()
Syntax & Examples
Array.forEach() method
The forEach() method executes a provided function once for each array element. It does not return a value.
Syntax of Array.forEach()
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.
Parameters
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. |
Return Type
Array.forEach() returns value of type void
.
✐ Examples
1 Using forEach() to iterate over an array
The forEach() method can be used to iterate over each element of an array and perform a specified action.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 4, 5]. - Define a callback function that logs each element to the console.
- Use
forEach(callbackfn)
to execute the callback function for each element in the array.
TypeScript Program
const arr = [1, 2, 3, 4, 5];
arr.forEach(element => console.log(element));
Output
1 2 3 4 5
2 Using forEach() to modify array elements
The forEach() method can be used to modify each element in an array.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 4, 5]. - Define a callback function that multiplies each element by 2 and logs the result to the console.
- Use
forEach(callbackfn)
to execute the callback function for each element in the array.
TypeScript Program
const arr = [1, 2, 3, 4, 5];
arr.forEach(element => console.log(element * 2));
Output
2 4 6 8 10
3 Using forEach() with index and array parameters
The forEach() method can be used with a callback function that takes the current element, index, and array as parameters.
For example,
- Create an array
arr
with string values ['a', 'b', 'c']. - Define a callback function that logs the current element and its index to the console.
- Use
forEach(callbackfn)
to execute the callback function for each element in the array.
TypeScript Program
const arr = ['a', 'b', 'c'];
arr.forEach((element, index) => console.log(`Element: ${element}, Index: ${index}`));
Output
Element: a, Index: 0 Element: b, Index: 1 Element: c, Index: 2
Summary
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.