JavaScript forEach vs for “oop to Iterate Through Arrays

JavaScript foreach Loop featured image

Purpose of forEach in JavaScript

The forEach method is generally used to loop through the array elements in JavaScript / jQuery and other programming languages.

You may use other loops like for loop to iterate through JavaScript array elements by using the length property of the array, however, for each makes it quite easier to iterate and perform some desired actions on array elements.

I have used for loop in several examples in JavaScript array tutorial; in this guide, I will show you how you can use forEach method for iteration in arrays.

Note: As such jQuery is also JavaScript’s library, so if you use this method in the jQuery code, it works the same way.

Syntax of using forEach method

This is how you can use the forEach method:

Array.forEach(function)

Where the array is the one you want to iterate through.

You may specify a function that is called for each iteration where you may perform certain actions like doing the calculation, printing, etc. of array elements.

As this function is called, this is invoked with three parameters.

  • The first parameter represents the value of the current element.
  • The second represents the index of that element.
  • While the third is the array in use.

See the following examples to learn how you can use JS forEach with arrays.

A simple example to display numeric array elements by forEach

In this example, I have created an array with numeric elements. After that, the forEach method is used where a JS function is called.

In the function, a JS command is used to display array elements in a div element.

Code with HTML and JS:

<!DOCTYPE html>
<html>
<head>
<style>
#div_demo {
  background: #4C9B79;
  height: 220px;
  width:40%;
  border-radius: 15px;
  padding:20px;
  font-size:18px;
  color:#fff;   
}
</style> 
</head>
 
<body>
<div id="div_demo">The array elements are:<br /></div> 
<script type="text/javascript">
 
var Numarray = [1,2,3,4,5];

Numarray.forEach(arrfunction);
 
function arrfunction(array_element) {
   document.getElementById("div_demo").innerHTML += array_element + "<BR>";
 
}
 
</script>


</body>
 
</html>

Output:

JavaScript forEach

You can see that a function, arrfunction, is called in the forEach method where array elements are displayed by using the array_element argument.

The same output by using for loop

By using the for loop with length property, this is how you may get the same output.

Code:

<!DOCTYPE html>
<html>
<head>
<style>
#div_demo {
  background: #4C9B79;
  height: 220px;
  width:40%;
  border-radius: 15px;
  padding:20px;
  font-size:18px;
  color:#fff;   
}
</style> 
</head>
 
<body>
<div id="div_demo">The array elements are (by using a for loop):<br /></div> 


<script type="text/javascript">

var Numarray = [1,2,3,4,5];
var num;

for (num=0; num < Numarray.length; num++){
    document.getElementById("div_demo").innerHTML += Numarray[num] + "<BR>";
    }
     

   
</script>

</body>
 
</html>

Output:

JavaScript for loop

JavaScript forEach example with a mixed array

Similarly, you can iterate through mixed arrays of JavaScript by using the forEach method.

In this demo, an array with mixed elements; numbers, and strings is created.

After that, the forEach loop is used where I call a function that displays the array elements.

Code:

<!DOCTYPE html>
<html>
<head>
<style>
#div_demo {
  background: #4C9B79;
  height: 220px;
  width:40%;
  border-radius: 15px;
  padding:20px;
  font-size:18px;
  color:#fff;   
}
</style> 
</head>
 
<body>
<div id="div_demo">A mixed array demo by forEach:<br /></div> 
<script type="text/javascript">
 
var Mixedarray = [1,"ABC",2,"DEF",3,"IJK",4,"LMN",5,"OPQ"];

Mixedarray.forEach(arrfunction);
 
function arrfunction(array_element) {
   document.getElementById("div_demo").innerHTML += array_element + "<BR>";
 
}
 
</script>


</body>
 
</html>

Output:

JavaScript foreach array mixed

You can see that array elements are displayed in a div as you execute this by using the forEach JS method.

A more complex example of forEach with HTML dropdowns

In this example, I have created two HTML dropdowns. As you select a continent from the left dropdown, the second will be filled by a few countries in that continent.

  • For that, I have created three arrays of continents in a JS function.
  • The function is called as you select a continent in the dropdown.
  • In that function, the selected value is checked by using if..else statement.
  • After that, the forEach method is used in each ‘if’ statement along with sending a specific function parameter.
  • In each function, JS code is used to populate the other dropdown with related countries.

See the demo and code online by clicking the image or link below:

JavaScript foreach dropdowns

Online demo and code

Following is the complete code, with JS and markup of the above example:

<!doctype html>

<html>

<head>



<script>

function myFunction() {



var selectedArr = (document.getElementById("continent").value);

var countries = document.getElementById('countries');



var arrEU = ["England","Germany","France", "Ireland","Poland","Italy"];

var arrAsia = ["China","South Korea","Singapore","Pakistan","India"];

var arrNAmerica = ["United States","Mexico"];



document.getElementById('countries').innerHTML = "";

if (selectedArr == "EU"){

arrEU.forEach(eufunc);

}

else if (selectedArr == "Asia"){

arrAsia.forEach(Asiafunc);

}

else {

arrNAmerica.forEach(NAmericafunc);

}



function eufunc(array_element){

var seloptions = document.createElement('option');

seloptions.innerHTML = array_element;

seloptions.value = array_element;

countries.appendChild(seloptions);

}



function Asiafunc(array_element){

var seloptions = document.createElement('option');

seloptions.innerHTML = array_element;

seloptions.value = array_element;

countries.appendChild(seloptions);

}



function NAmericafunc(array_element){

var seloptions = document.createElement('option');

seloptions.innerHTML = array_element;

seloptions.value = array_element;

countries.appendChild(seloptions);

}



}

</script>



<style>

.div_demo {

background: #5AB65A;

height: 100px;

width:30%;

border-radius: 15px;

padding:20px;

font-size:22px;

color:#fff;

}

</style>





</head>

<body>



<div class="div_demo">

<select id="continent" onChange="myFunction()">

<option>Select Continent</option>

<option value="EU">Europe</option>

<option value="Asia">Asia</option>

<option value="NAmerica">North America</option>

</select>



<select id="countries">

<option>Countries</option>

</select>

</div>





</body>

</html>

A final word about forEach

The forEach method is an extension of ECMA-262 Standard.

The preferred way to iterate elements is still a for loop rather than using the forEach JavaScript method due to performance reasons.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!