๐Array.forEach()
forEach()
**forEach
**method will call the function provided once for each element in the array preserving the order. This function provided can take in 3 different arguments: element
, index
, array
. Be sure that the order in which you pass these parameters follow the order.
The for
loop is probably one of the first looping mechanisms you learned about when diving into JavaScript.
The for
loop above takes 3 statements within it:
let i = 0
, which executes before the loop startsi < 5
, which is the condition for running the block of code within your loopi++
, which runs after each iteration of your loop
The result of those three statements is that the for
loop executes the code within it, which is console.log(i)
. Our i
starts at 0, and as long as i
is smaller than 5, weโll run the code block. However, after each loop, we add 1 to our i
, as shown by the third statement, i++
.
Letโs dive into something a little fancier for this for
loop. Letโs assume that we have an array with some objects in it:
Letโs say we wanted to use a for
loop to iterate over each object within the foodArray
. We would alter the condition and use i
as the numeric index to access the values within foodArray
.
What About forEach?
Like the for
loop, the forEach
method can also achieve the same results:
How is that possible?
The forEach
method exists within all arrays. In our case, foodArray
is an array that inherits all of the various methods from Array.prototype
. For the forEach
method, we pass in a function that will be executed in each iteration.
Which Should You Use?
It really comes down to the preference of the developer. However, here are some things to consider when choosing between a for
loop and the forEach
method.
1. forEach keeps the variableโs scope to the block
The good thing about forEach
is that the callback function within it allows you to keep that variable within the forEach
โs scope. If youโve assigned a variable outside and re-use it within the forEach
, the outside variable retains its value.
Normally, you would try to avoid naming a variable twice like in the example above. It's just to make a point!
2. Lower chance of accidental errors with forEach
When using the forEach
method, youโre calling on the Array.prototype
method in relation to the array directly. When you use a for
loop, you have to set up a variable to increment (i
), a condition to follow, and the actual increment itself.
Based on the example above, letโs say that we wrote a for
loop like this:
I changed my condition from <
to a <=
. Instead of ending at 3, which is less than the length of my array, it goes all the way to 4. Since thereโs nothing in our array at index 4, it returns an undefined. This type of off-by-one-bug is a logic error when your iterative loop iterates one more or less than you anticipated.
Using a forEach
loop, this can be avoided.
3. forEach is easier to read
Again, this is down to the discretion of the developer, but hereโs why I feel that the forEach
method is a little cleaner than the for
loop.
In a forEach
method, we pass each food type within that iteration into the callback. A for
loop needs you to access the array using a temporary i
variable. While this might not seem very messy in the beginning, it can get more cluttered when you begin to add more code.
Thereโs a bit going on in the code above. Having to use the temporary i
and j
variables can add a lot of confusion to your code. Hereโs what it would look like as a forEach
instead:
Weโve gotten rid of the temporary counter variables and it requires fewer lines of code!
4. You can break out of a for loop earlier
One main reason why I would use the for
loop is if I needed to break out of a loop early. If you wanted to only return a certain food in your array, you could use an if
statement to check if your criteria matches, and then break out from the loop. The forEach
method would iterate over each food, which could lead to performance issues.
Hereโs an example of what the for
loop would look like if you broke out of it early:
When we use the break
keyword, we can stop the loop from continuing once weโve found the condition we were looking for.
Last updated