![]() ![]() If you are not going to use the resulting new array from a map() operation, such as in the example above where you are only logging the elements, then you should not use map(). So you have to ask yourself if you need the returned array. So when the loop finishes map() returns a whole new array for us with the results of the iteration. The reason lies in the fact that map() returns a new element on each iteration and pushes it into a new array. forEach() is what we should have used all along for something like this. So what’s going on? Well, the truth is this example of map() is an anti-pattern that should not be used. But, removing the index part, looks exactly identical to our first forEach() example. I used this example to show how map() gives us the index of the element in the array. Products.map( (product, index) => console.log(product, index)) Let me bring back an example we used in the previous article: But there is one fundamental difference between the two, and in that difference lies the decision of which to use. If you’ve read the previous article in the series about map() you would rightly be thinking that this sounds suspiciously the same. But of course, to use it correctly we have to dig a little deeper. So in the opening example, we saw that the function we provided logs the current array element to the console. It will execute the function we provide for each element of the array we want to iterate on. It does only one thing but it does it very well. So what is the Array.forEach() method? In essence, this is a very simple method. It’s not a requirement to read the previous articles in order to follow along with the examples in this article. In this article, we will take the example established in the previous articles and show how forEach() can help us. Instead, we’ll take a deep look at how the method works, why we need it, and what it would look like in a typical modern front-end codebase. There won’t be a lot of mentions of your pets and friends either I’m afraid. I will try to avoid `foo` and `bar` or overly complex examples. In this “ JavaScript iteration in the real world” series of articles, I want to share with you some of the most common JavaScript iteration methods using examples that resemble as closely as possible what their usage looks like in the real world. Products.forEach(product => console.log(product)) Log to the console each element of the array ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |