Skip to content

Array forEach JavaScript | Function

  • by

JavaScript forEach() function with an array used to execute a function on each item in an array. This method calls a function for each element in an array if the array is not empty.

array.forEach(function(currentValue, index, arr), thisValue)

Example Array forEach JavaScript

Simple HTML example code.

<!DOCTYPE html>
<html>
<head>

  <script>
    const array1 = ['a', 'b', 'c'];

    array1.forEach(element => console.log(element));
  </script>
</head>
<body>

</body>
</html>

Output:

Array forEach JavaScript

More example

Get the sum of a given number

  <script>
    let sum = 0;
    const numbers = [10, 20, 30];
    numbers.forEach(myFunction);

    function myFunction(item) {
      sum += item;
    }
    console.log(sum)
  </script>

Output: 60

Multiply each element of the array by 10:

  <script>
    let sum = 0;
    const numbers = [10, 20, 30];
    numbers.forEach(myFunction);

    function myFunction(item, index, arr) {
      arr[index] = item * 10;
    } 
    console.log(numbers)
  </script>

Output: Array(3) [ 100, 200, 300 ]

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading