The forEach loop in JavaScript

This tutorial introduces the forEach loop in JavaScript. The forEach loop can be used to easily call a function once for each element in an array. As the loop works through each element in the array, the function is called once for each element.

Here is the basic syntax used in the forEach loop where the function myFunction is called on each element in the array myArray:

var myArray = ["one", "two", "three", "four"];

myArray.forEach(myFunction);

function myFunction(element) {
   // code in loop goes here
  console.log(element);
}

Watch the video below or scroll down for the sample code.

Here is an example of a basic forEach loop where the loop will call the displayUser() function once for each element in the users array. The function will just display the user in the console. The parameter ‘user‘ in the displayUser function represents the element in the array being process in each iteration of the loop.

var users = ["Homer", "Marge", "Bart", "Lisa", "Maggie"];

users.forEach(displayUser);

function displayUser(user) {
  console.log(user);
}

After running this code, the output in the console will look like this:

foreach1param

In the example below, the displayUser function has two parameters: user and index. The index parameter will be used to access the index of the element in the array being processed in each iteration of the loop.

var users = ["Homer", "Marge", "Bart", "Lisa", "Maggie"];

users.forEach(displayUser);

function displayUser(user, index) {
  console.log("User" , user , "is in index" , index);
}

After running this code, the output in the console will look like this:

foreach2param

Full code

Here is the full code for the examples above.

HTML code:

<html>
    <head>
        <title>forEach loops</title>
        <script src="script.js"></script>
    </head>
        
    <body>

    </body>
</html>

JavaScript code (using one parameter in the function):

var users = ["Homer", "Marge", "Bart", "Lisa", "Maggie"];

users.forEach(displayUser);

function displayUser(user) {
  console.log(user);
}

JavaScript code (using two parameters in the function):

var users = ["Homer", "Marge", "Bart", "Lisa", "Maggie"];

users.forEach(displayUser);

function displayUser(user, index) {
  console.log("User" , user , "is in index" , index);
}

Next tutorial: Objects, properties and methods