TypeScript forEach

The forEach() method is an array method which is used to execute a function on each item in an array. We can use it with the JavaScript data types like Arrays, Maps, Sets, etc. It is a useful method for displaying elements in an array.

Syntax

We can declare the forEach() method as below.

The forEach() method executes the provided callback once for each element present in the array in ascending order.

Parameter Details

1. callback: It is a function used to test for each element. The callback function accepts three arguments, which are given below.

  • Element value: It is the current value of the item.
  • Element index: It is the index of the current element processed in the array.
  • Array: It is an array which is being iterated in the forEach() method.

Note: These three arguments are optional.

2. thisObject: It is an object to use as this when executing the callback.

Return Value

It will return the created array.

Example with string

The corresponding JavaScript code is:

Output:

TypeScript forEach

Example with number

Output:

TypeScript forEach

Disadvantage of forEach()

The following are the disadvantages of the use of the forEach() method:

  1. It does not provide a way to stop or break the forEach() loop.
  2. It only works with arrays.

Next TopicTypeScript Map




Contact US

Email:[email protected]

Typescript forEach
10/30