JavaScript Array forEach()

Posted by

Introduction to JavaScript Array forEach()

The forEach() method of the JavaScript Array object executes a provided function once for each element in an array. It is used to iterate over an array and perform a given action on each element of the array. It is a higher-order function, which means it takes a function as a parameter.

Syntax

The syntax of the forEach() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

arr.forEach(callback[, thisArg])

[/dm_code_snippet]

Where:

  • arr is the array to execute the callback function on.
  • callback is the function that will be executed on each element of the array.
  • thisArg (optional) is an argument that can be used to set the value of this inside the callback function.

Example

Let’s look at an example of how to use forEach(). Consider the following array of numbers:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let numbers = [1, 2, 3, 4, 5];

[/dm_code_snippet]

If we want to print each element of the array, we can use the forEach() method as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

numbers.forEach(function(number) {
  console.log(number);
});

[/dm_code_snippet]

This will print the following output in the console:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

1
2
3
4
5

[/dm_code_snippet]

Parameters

The forEach() method takes a single parameter, which is a callback function. This callback function will be executed once for each element in the array.

The callback function takes three parameters:

  • currentValue is the value of the current element being processed in the array.
  • index is the index of the current element being processed in the array.
  • array is the array that forEach() was called upon.

Return Value

The forEach() method does not return a value.

Browser Support

The forEach() method is supported by all modern browsers, including IE9 and above.

Conclusion

In this tutorial, we learned how to use the forEach() method of the JavaScript Array object. We looked at the syntax, parameters, and return value of the method. We also looked at an example and discussed the browser support.