JavaScript Asynchronous Programming with JavaScript Understanding Promises Handle Multiple Promises with Promise.all

Why use map() when you could just use forEach()?

Guil uses map() in the generateHTML function, but map returns a new array. Why doesn't he just use forEach() which simply iterates over each item in the array? Am I missing something?

1 Answer

Steven Parker
Steven Parker
207,003 Points

If you used "forEach", you'd need to first create a new empty array, and then inside the body of the forEach you would push the current item onto the new array.

Using "map" saves you a couple of steps since it's designed to return a new array.

Yeah but in the video he didnt need a new array. He just needed to iterate over each object in the array and generate html for it and that's it.

Steven Parker
Steven Parker
207,003 Points

You didn't give a time index, but I hunted down the part you are referring to — and yes, a "forEach" should work just fine there.