r/learnjavascript • u/fahim_h_sh • Oct 31 '25
array.forEach - The do-it-all hammer... XD
Is it just me, or everyone thinks that more or less every array operator's purpose can be served with forEach?
0
Upvotes
r/learnjavascript • u/fahim_h_sh • Oct 31 '25
Is it just me, or everyone thinks that more or less every array operator's purpose can be served with forEach?
1
u/delventhalz Oct 31 '25
Well, forEach is just a loop, so certainly any task which requires looping over an array can be accomplished by forEach (though personally, if I need a plain loop I prefer for...of).
That said, JavaScript is an expressive language, particularly when looping over arrays, so there are probably more specific array methods you could use depending on the task.
map: transform each element in an array into some other element
flatMap: transform each element in an array into zero or many other elements
filter: get only a subset of matching elements in an array
find: get one specific matching element
some: check if any element in an array matches
every: check if all elements in an array match
includes: check if a specific value is in an array
toSorted: sort an array
And many more!
So forEach is a great start. It's working for you and helping you solve problems. That's great. As you keep practicing, start looking for places some of these other methods might help you as well (map and filter in particular come up a lot). Happy coding!