DEV Community

amsfreeman
amsfreeman

Posted on • Updated on

When and how to use forEach and map in Vanilla JS vs React

When I began learning to code in my software development bootcamp, we started with Vanilla Javascript. By the end of three weeks, I started to feel some confidence with Vanilla JS. I knew lots of ways to accomplish things, and I felt relatively comfortable with syntax. Then came React, and a whole new process to learn. Some old friends made reappearances, but there were many new things to learn. Today, I am going to talk about one of the things that took me awhile to fully grasp, and hopefully shed some light on this difference to others.

When learning Vanilla JS, forEach() was a trusted and helpful friend. Whenever, I needed to iterate through an array of objects and get information from each object in the array, forEach() was there for me. I seemed to use it constantly.

As an example of its usage, I would sometimes have information coming from an API or another source such as a db.json. Let's say that information was an array of book objects, and each book object had an id, a title, an author, and a rating out of 5.

So if I had this array of objects as shown below:

"books" : [
{
"id": 1,
"title": Little Women,
"author": Louisa May Alcott,
"rating": 4
},
{
"id": 2,
"title": The Picture of Dorian Gray,
"author": Oscar Wilde,
"rating": 4
},
{
"id": 3,
"title": Moby Dick,
"author": Herman Melville,
"rating": 3
},
{
"id": 4,
"title": Wuthering Heights,
"author": Emily Bronte,
"rating": 4
}
]
Enter fullscreen mode Exit fullscreen mode

[1].

I could then iterate through my books with a forEach() loop and console log them as shown below:

function allBooks(arrayOfAllBooks){
  arrayOfAllBooks.forEach(book => {
    console.log(book)
})}
Enter fullscreen mode Exit fullscreen mode

[1].

Perfect, wonderful!

However, there is an issue when working with React JS. Namely, forEach() returns undefined. On the other hand, map() works wonderfully in React as it returns a new array! Additionally, forEach() cannot be used with other array methods, but map() can. This allows map() to be used with array methods, such as filter(), which is also important in React[2].

Below there is a great way to use map in React, while using the same book data from above. The book container will contain all the books in the book array. The book components will take the full book array and map through it, returning book card after book card until the process is complete. In the mapping, passed down to the book card component will be each book, with an key, id, name, author, and rating. Finally, the book components will be returned inside of a div.

function BookContainer({bookArray}){
  const bookComponents = bookArray.map(book => {
    return(
      <BookCard 
        key={book.id}
        id={book.id}
        name={book.name}
        author={book.author}
        rating={book.rating}
      />
    )
  })
  return (
    <div>
      {bookComponents}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

So we can see the importance of map() in React JS, versus forEach() in Vanilla JS. However, it should be noted that forEach() can still be used in certain scenarios in React JS. For example, forEach() can be used when you need to call a function for every element in an array. In this case, forEach() cannot be used within JSX, but must be used outside of it [3].

Ultimately, we can see the power of forEach() in Vanilla JS and map() in React. Knowing the difference between these and being able to explain why one should be used versus the other is important, and makes coding easier. While it took me some time to understand these differences, I feel that I am now well on my way to a deeper understanding, and look forward to using this knowledge to help my coding, both in Vanilla JS and React.

(Cross posted on Medium at: When and how to use forEach and map in Vanilla JS vs React).

[1] Author Unknown. "5 Ways Javascript Loop Through Array of Objects." Tutorials Tonight. https://www.tutorialstonight.com/javascript-loop-through-an-array-of-objects#foreach-loop (accessed June 25, 2023).

[2] Imran Alam. "What is difference between forEach() and map() method in JavaScript?" Tutorials Point. https://www.tutorialspoint.com/what-is-difference-between-foreach-and-map-method-in-javascript#:~:text=The%20map()%20method%20is%20used%20to%20transform%20the%20elements,used%20with%20other%20array%20methods (accessed June 25, 2023).

[3] Borislav Hadzhiev. "How to use the forEach() method in React." bobbyhadzblog. https://bobbyhadz.com/blog/react-foreach (accessed June 25, 2023).

Top comments (0)