Both map
and filter
do not modify the array. Instead they return a new array of the results. Because both map
and filter
return Arrays, we can chain these functions together to build complex array transformations with very little code. Finally we can consume the newly created array using forEach
. In this lesson, we will learn how to build nontrivial programs without using any loops at all.
Hi Jafar,
Great tutorial, Now I am eager to replace my loops with these functions in my code. Two questions for you : 1 ) What will be the performance ramifications of chaining Array map and filter methods when compared to a single loop or a single forEach? 2) You mentioned looping is not an option when the data is coming asynchronously. I didn't understand this point. Why will looping not be an option in such scenarios?
When would you use forEach over .map as they both seem to do the same thing to me.
When would you use forEach over .map as they both seem to do the same thing to me.
Hey Ryan, they seem similar for sure, but map
always produces a new collection and forEach
simply iterates over a collection. Map is going to be the goto preference, in general.
Thanks Joel!
First that all, thas for this series. I have a question: wht do you mean by "However, loops are no good to us when we're trying to work with data that's arriving asynchronously like with events." Would you mind sharing a fiddle? Thanks in advance
I mean that you can't wait for an event in a loop. You have to attach an event handler. Furthermore you cannot repeat an asynchronous operation in a loop, because loops run their body immediately whereas async operations are resumed in a callback.
This is simpler:
function getStockSymbols(stocks, minPrice) { return stocks .filter((stock)=> stock.price>= minPrice) .map((stock)=>stock.symbol) }
I don't necessarily agree with what Jafar says, "write complex programs, all! without ever writting a loop" .... so what do you think the function is doing??? is looping over the elements in the array and at the end of the day is blocking io!