TypeScript Array forEach() Method
Last Updated :
11 Jul, 2024
Improve
The forEach() method in TypeScript calls a specified function for each element in an array. It takes a callback function executed on each element and an optional thisObject parameter to use as this context. It enhances iteration readability and efficiency.
Syntax
array.forEach(callback[, thisObject])
Parameters
This method accepts two parameters as mentioned above and described below:
- callback: This parameter is the Function to test for each element.
- thisObject: This is the Object to use as this parameter when executing callback.
Return Value:
This method returns created array.
Example 1: Basic Usage
In this example we initializes an array arr with numbers and uses the forEach method to iterate through the array.
// Driver code
let arr: number[] = [11, 89, 23, 7, 98];
// printing each element
arr.forEach((value: number) => {
console.log(value);
});
Output:
11
89
23
7
98
Example 2: Printing Squares
This TypeScript code declares an array of numbers and uses the forEach method to print the square of each element, with type annotations ensuring values are correctly recognized as numbers.
// Driver code
let arr: number[] = [1, 2, 3, 4, 5];
// printing square of each element
arr.forEach((value: number) => {
console.log(value * value);
});
Output:
1
4
9
16
25