Why I stopped using ‘for’ loops and started mapping instead
In this article, I will show how in React, the ‘map’ method is often the recommended one to use.
Now, let’s say we have a component we wish to render multiple times, a beginner would probably do this:
Since you can’t return a ‘for’ loop directly, you need to create a new array that will contain the components to return.
So if your goal is just to render UI, a ‘for’ loop is fine. However, if your goal is to create a complex re-usable component, the preferred method is ‘map’:
This method takes a callback function with three parameters: the current value while iterating, the current index and the array on which you iterate. Then it returns a new array of the resulting components. The key prop makes it so each ‘ChildComponent’ created is unique, so when you update a value from one component, others won’t be re-rendered either.
You can’t exit a ‘map’ with a break condition like you would with a ‘for’ loop. However, since the ‘map’ function returns an array, you can chain the result with other functions such as ‘filter’:
Note: The filter method takes a function in its parameters and returns a new array with all elements that validate the test from the function.
The ‘map’ function will always return an array while the ‘for loop’ approach you define the return value — if there is any.
As you can see, it’s not quicker because of the callback function that is called on every item, but the code is cleaner, quicker to implement and more powerful.
In my opinion, ‘map’ really shines when you need to extract specific data from the result of an API call. Let’s say you need to extract the rating value for a specific movie from an API:
Here we will retrieve the Rotten Tomatoes rating for this movie using the ‘map’ method:
The same code with ‘for’:
As you can see, you cannot return a ‘for’ loop directly. That is why you have to create a variable that holds the extracted value. As an aside, you cannot check the values inside this loop with an ‘if’ since conditional operators (‘&&’) won’t work, making the code less readable than just using ‘map’ directly.
Angular is all about components that have to interact with one another. How can you change data of a component when using another one?
Just like React and Angular, Vue.js gives you the possibility to lazy load some parts of your application.