What is JavaScript forEach?

The forEach is a method of arrays that is used to call a given function for each element of the array in JavaScript. The function runs only for present elements in the forEach method.

The elements added after the forEach method is used, will not be shown.

Following is the syntax which is followed by examples of using the forEach JavaScript method.

See a forEach method example

Note: if you meant JavaScript for each loop then this is now deprecated in JavaScript. Read more here about the JavaScript for each..in and its alternative.

Syntax of JavaScript forEach

The basic syntax of array forEach method is:

Array_name.forEach(callback_function[, thisArg])

Where:

  • Callback_function is the function to be executed for each element in an array.
  • thisArg is the value to be used for this.

As a function is called in forEach, this is being invoked with three arguments as follows:

  1. The value of element of array
  2. The index of element
  3. The array in use

You can get these arguments; especially value and index are quite useful that can be used as per requirement of the project. The example below will show you how to get these arguments.

A forEach example

Following is an example of using the forEach array method. We have created an array of four numbers (1,2,3,4) for illustration purpose.

The JS foreEch method is called with a callback function, “arrfunction”. The function will get three arguments and in this example, we will simply display array index along with element value.

Click the following link or image to see forEach in action.

Experience this example online

A forEach example with missing element value

The following example shows what happen if an array element value is missing as using the forEach JavaScript method. See this example by clicking the link below:

Experience this example online

You can see, the third element is missing in the array. While displaying array elements by using the forEach method, it will not display undefined.

Note that, you cannot stop or break the forEach method.

Further reading: JavaScript array