Sometimes we need to use the forEach() method, which applies a callback function to every item in the array. However, unlike map(), forEach() does not return anything. It only has side effects, not a return value. Because it does not return any values, you can not use the forEach() method within the JSX code.
With forEach() method, you need to do something with values after the callback function is applied. If you do not push() or even console.log() the values, then they will disappear. forEach does not change the array itself. It only takes items in the array and applies a callback function.
forEach() vs map()
The main difference is that forEach is primarily used for its side effects. The callback function passed to forEach is primarily used for side effect. Map() on the other hand applies the callback function to every item and creates a new array composed of modified elements.
For loop instead of forEach()
Personally, I like forEach() and its callback function approach. The for loop is far too convoluted for my tastes. Instead of setting index and keeping track of it, I prefer to create a function that automatically applies the callback function on every element.
Both forEach and for loop require multiple lines of code to generate a new value. For this reason, you can not use them to create elements directly in the JSX. For example, if you have a chat window, and an array of chat messages, you can render messages for every item in the array. React allows you to improve chat’s UX. For example, scroll to bottom of the chat every time user enters a new message. However, you can use both to create new arrays outside of JSX and then reference those values within JSX.