How to use javascript foreach method

The forEach

The forEach is a method of arrays that is used to call a given function for each element of the array. The function runs only for present elements in the forEach method. Elements added after the forEach method is used, will not be shown.

Following is the syntax followed by examples of using 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 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 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.

Javascript for each example

Following is an example of using forEach array method. We have created an array of four numbers (1,2,3,4) for illustration purpose. Then 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 to see forEach in javascript 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 using 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 forEach method.

Also see Javascript array | Javascript for

Was this article helpful?

Related Articles

Leave A Comment?