forEach Method
forEach is an array method that runs a function for each item.
You pass the helper function in.
Think of a teacher handing every student the same worksheet.
Basic forEach
Value and index
Side effects
Limits of forEach
Basic use
Call array.forEach(function).
Value and index
The callback can take the item and its index.
Arrow style
Many people write a short arrow function.
Good for side effects
forEach is nice when you want to print or update something.
It does not build a new array for you.
No easy break
You cannot use break inside forEach the same way as in a for loop.
If you need to stop early, a for or for...of loop is clearer.
map vs forEach
Use map when you want a new array of results.
Use forEach when you just want to do something with each item.
Tip: If you need a returned list, reach for map. If you only need actions, forEach is fine.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.