JavaScript forEach() | Call a Function for Each Item in an Array

The JavaScript forEach() method is used when we need to execute a function for each element of a specified array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      const numbers = [12, 32, 43, 54];
      let sum = 0;

      numbers.forEach(findSum);

      function findSum(x)
      {
         sum += x;
      }

      document.getElementById("xyz").innerHTML = sum;
   </script>
   
</body>
</html>
Output

JavaScript forEach() Syntax

The syntax of forEach() method in JavaScript, is:

array.forEach(functionName(currentElementValue, currentElementIndex, currentElementArray), thisValue)

The functionName and currentElementValue are required.

Note - The functionName refers to a function to execute for every elements of array.

Note - The currentElementValue basically refers to a variable that will be used to pass as an argument to the function that of course indicates to the current value/element of the specified array.

Note - The currentElementIndex refers to the index of the current element

Note - The currentElementArray refers to the array of the current element.

Note - The thisValue refers to a value passed to the specified function functionName as its this value. The default value is undefined

JavaScript Online Test


« Previous Tutorial Next Tutorial »