forEach loops
Coding with JavaScript
🕑 This lesson will take about 10 minutes
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:
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 processed in each iteration of the loop.
After running this code, the output in the console will look like this:
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.
After running this code, the output in the console will look like this:
Callback function - example
In this example, a callback function is used. A callback function is executable code that is passed as an argument to another piece of code. In the example below, the executable code is passed as a parameter into the forEach loop rather than being specified in a separate defined function.
Next lesson: The getElementById() method