Using the forEach Method in Javascript
Before learning how to use the forEach
method in Javascript, we are going to understand how this method is similar to using a for
loop. Please follow along in order to understand what is happening.
Using the For loop
Let’s create a new array
let animals = ["Chicken", "Horse", "Pig", "Dog", "Cat"];
We are going to iterate through the array of animals to log on our console each animal. In order to do so, we will use the for loop. According to documentation, the for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
Syntax
for ([initialization]; [condition]; [final-expression])
statement
Let use this information to implement our for loop:
Let’s Clarify the for loop:
- The first argument
let i = 0;
We are setting 0 to a variable. We will use this afterwards to get access of an animal at a specific index. - The second argument
i < animals.length
This tell us as long asi
which is 0, is less than the length of the animals array, we want it to increment. - The third argument `i
++
` This is our increment. More about this, click here for more information.
The result is after we iterate through the animals array, we console log the animals as individual animals by acessing the animal with it’s index. When we call animals[i]
we are basically saying give me the animal from the animals array with this index. Think of how do you access the first animal. We would do something like this: animals[0]
With the for loop, everytime we loop the animals.length
we set the first argument to the next number because we increment it.
Using the forEach Method
We can simplify the above code with using the forEach method. According to documentation, the forEach()
method executes a provided function once for each array element.
Syntax
arr.forEach(callback(currentValue[, index[, array]]) {
// execute something
}[, thisArg]);
Let use this information to implement our forEach loop:
Let’s Clarify the forEach loop:
- Using the forEach method calls an anonymous function. This function will have an argument of animal.
- Using forEach, we do not have to set a variable to equal 0 and increment it. We will not need to access the animal with a specific index number.
- When console log the animal, we get the same response back on our console as the for loop.
Reading all of this information and seeing these examples, which one would you prefer to use?
For more information about these two methods, make sure to click the “According to documentation”. Check out this video below for more help, or just click here.