JavaScript Array forEach() method


The code below demonstrates the forEach() method on a JavaScript array using a modified example from w3schools.com. The forEach() method calls a provided function once for each element in an array, in order. forEach() does not execute the function for array elements without values.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to list all the items in the array.</p>
<button onclick="numbers.forEach(myFunction)">Try it</button>
<p id="demo"></p>

<script>
demoP = document.getElementById("demo");
var numbers = ['apple', 9, 16, 25];

function myFunction(item, index) {
    demoP.innerHTML = demoP.innerHTML +  item + "<br />"; 
    }
</script>

</body>
</html>

jsforeach

Here is the output in the browser after you click the Try It button. In MyFunction() you need to include demo.innerHTML after the equals sign otherwise the output will only be the last item in the array becase it will overwrite the previous array elements. Also notice that the array can contain text and numbers.

Here is another forEach() example from w3schools.com. In this example we are adding up the numbers in the array and displaying the total to the user. After you click the Try It button you will see the total as the HTML of the span tag that is within the paragraph tag.

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the sum of the numbers in the array.</p>
<button onclick="numbers.forEach(myFunction)">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var sum = 0;
var numbers = [65, 44, 12, 4];

function myFunction(item) {
    sum += item;
    demo.innerHTML=sum;
    }
</script>
</body>
</html>

Below is another example from w3schools.com. myFunction() in this example takes three arguments. The first two must be item and index respectively, but the third can be what you want, such as arr or myArray or ay or whatever as long as it is not a reserved word.

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get multiply every element except the second element in the array with a specific number.</p>
<p>Multiply with: <input type="number" id="multiplyWith" value="10"></p>
<button onclick="numbers.forEach(myFunction)">Try it</button>
<p>Updated array: <span id="demo"></span></p>
<script>
var numbers = [65, 44, 12, 4];

function myFunction(item,index,arr) {
	if (index != 1) { // except the second element in the array
    	arr[index] = item * document.getElementById("multiplyWith").value;
    }
    demo.innerHTML=numbers;
    }
</script>
</body>
</html>

Leave a comment

Your email address will not be published. Required fields are marked *