top of page

TypeScript 'forEach' Method

TypeScript is a superset of JavaScript that provides static type checking, which can help detect errors before runtime. It also supports many features of object-oriented programming languages, like classes and interfaces. One helpful feature of TypeScript is the forEach method, which allows us to iterate over an array and perform an action on each element. In this article, you will explore the forEach method in TypeScript, including its syntax, usage, and examples.


One of the main advantages of using forEach in TypeScript is that it provides type checking at compile time, which can help detect errors before the execution of the code. This is useful when working with complex data types or performing operations that involve multiple steps.


Overall, forEach is a helpful method in TypeScript that can simplify many tasks. It allows us to perform operations on each element in an array, and its static type checking can help ensure that our code is reliable and efficient.

Syntax of TypeScript forEach Method

The forEach method in TypeScript is very similar to its JavaScript counterpart, with the following syntax:

array.forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; 

The forEach method takes two parameters: a callback function and an optional thisArg parameter.

The callback function takes three arguments:

  • value: The current element being processed in the array.

  • index: The index of the current element being processed in an array.

  • array: The array that forEach is being applied to.

The thisArg parameter is optional and represents the value of the callback function which will be used when executed.

Usage of TypeScript forEach Method

To use the forEach method in TypeScript we need an array to iterate. Here is an example array:

const fruits: string[] = ['Apple', 'Banana', 'Cherry', 'Orange', 'Blueberry']; 

We can then use the forEach method to iterate over each element in the array and print it to the console:

// Define an array of fruit names
const fruits: string[] = ['Apple', 'Banana', 'Cherry', 'Orange', 'Blueberry'];

// Define a callback function to be called for each element in the array
function printFruit(fruit: string, index: number, arr: string[]) {
  console.log(`Element at index ${index} is ${fruit}`);
}

// Use the forEach method to call the printFruit function for each element in the array
fruits.forEach(printFruit);

In the above code, we have defined a callback function that takes two arguments: fruit and index. We then call the console.log method to print the current element and its index to the console.

The output of this code will be:









Note that we can also use arrow functions to define the callback function more concisely:

// Define an array of fruit names
const fruits: string[] = ['Apple', 'Banana', 'Cherry', 'Orange', 'Blueberry'];

// Use an arrow function as the callback for forEach
fruits.forEach((fruit: string, index: number, arr: string[]) => {
  console.log(`Element at index ${index} is ${fruit}`);
});


Use 'thisArg' Parameter in TypeScript forEach Method

The thisArg parameter allows us to specify the value of this that the callback function will use when executed. This can be useful when working with object-oriented code.

Here is an example of using the thisArg parameter to call a method on an object for each element in an array:

// Define an object to use as the "this" value inside the callback
const printFruit = {
  fruitPrefix: "Fruit Name: ",
  print: function(fruit: string, index: number, arr: string[]) {
    console.log(`${this.fruitPrefix}${fruit}`);
  }
};

// Define an array of fruit names
const fruits: string[] = ['Apple', 'Banana', 'Cherry', 'Orange', 'Blueberry'];

// Use the printFruit object as the "this" value inside the callback
fruits.forEach(printFruit.print, printFruit);

In this example, we define an object called printFruit that has two properties: fruitPrefix, which is a string that we'll use as a prefix for each fruit name, and print, which is a function that takes the same three parameters as before (fruit, index, and arr). Inside the print function, we log each fruit name to the console with the fruitPrefix.

The output of this code will be:









Where you can use the TypeScript ForEach Method

The 'forEach' method is a versatile tool to perform different operations on each element. The use case of the 'forEach' method is:

  1. You can perform an asynchronous operation on each element of an array.

  2. It will help you to convert an array to a different format, such as an object or a string.

  3. If you are working with the Document Object Model (DOM) in the web application, you can use this method to collect DOM elements and manipulate them as needed.

  4. You can use the method to log each element to the console or perform other debugging operations.

  5. You can also use this method to search for an element, filter an array based on your criteria, and also modify the elements of an array as needed.

Conclusion

The forEach method in TypeScript allows us to iterate over an array and perform an action on each element. Its syntax is similar to the JavaScript forEach method, with the added benefit of static type checking. We can use the callback function to perform any action we want on each element, including logging, modifying, or deleting it.

0 comments
bottom of page