forEach
Explore the JavaScript forEach method to understand its unique role in performing side effects on array elements. Learn how it contrasts with map and filter by not returning new arrays but instead affecting external variables, helping you write clearer and intentional code.
We'll cover the following...
forEach
Array.forEach is different from map & filter. You may find it easier to reason about. map & filter return us new, altered arrays based off of the original array. forEach returns us undefined. It’s used purely to do something with the items in an array, not to get a new array out of it.
Here’s an example. The following two code blocks are equivalent.
We’re taking an array of individual words and logging each to the console. We’re also concatenating them by adding them all one by one to our initially empty string str.
forEach vs map & filter
We’re using forEach to implement a side effect. The callback we pass in isn’t meant to be a pure function. It’s meant to affect something outside its own local scope. This contrasts with map and filter which should ideally be given pure functions.
We could do this same thing with map or filter.
Both of these blocks above do the same thing for us. We pass in the same exact callback that we gave to forEach. Although map and filter are still providing us a return value, we’re not using it.
Why to use forEach
The reason to use forEach over either of those functions is to make it clear that we want to affect the outer scope. When we see map and filter, by convention, we should expect the functions to do nothing except return us a new array.
forEach is essentially meant to be an impure version of map. An engineer will typically use this method to signify the intent of changing an external value by using the array.
We should follow this convention when we write code. The use of forEach shows a different intent than any of the other functions.
Like map and filter, forEach passes in two additional arguments as well, the index and original array.
You should now be able to write your own version of forEach. If you want, go ahead and give it a try!
Writing forEach Exercise
That’s it for forEach.