Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use .map Instead of a for loop to Iterate over an Array

    Chris AchardChris Achard

    Whenever you want to loop over an array and create a new array based on each element in the first array, it's possible to use the map function on the array, instead of using a for loop. There are a few advantages to map over for, including shorter code that is more composable - meaning you can easily extract and reuse the function(s) that you're using. You can also chain multiple map calls together.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: If we have an array of numbers and we want to turn that array into an array of strings, for each string has the number first, and the text days ago, except is the number is a one, where the text should be day ago.

    Then, one way we can do that is to make a new array and use the for loop to iterate over the entire array. In each iteration, we'll extract the number and build the string that we want, and push that on to the new array that we made.

    If we log the output, the network's just fine. Whenever we're looping over an array like this and pushing something on to the array in each iteration, we can simplify the process by using the map function on the original array.

    If we start without array and call down map that is a function, and the first argument to the function is the element from the array which is the number that we want in this case.

    From this function, we need to return whenever we want to go into a new array which is a new string which has days ago with the number, and now the entire map function returns the new array, so we can set this to a new array.

    If we log it and run it, we get exactly the same output, but the code is shorter and we don't need these temporary variables. Another reason to use map, is because it's easy to extract the inner function. Once we give that function a name, we can pass it into the map function by itself, because map just takes a function.

    It doesn't matter, if it's an inline function or reusable function from someone else. When we log and run that, it prints out the same thing again. Also, because the map function returns an array, it makes it very easy to chain the map functions together.

    If we had another function which prepends the text last accident to the input text, we can start by calling map with the days ago function like before and in just chain on another map, which is the new last accident function.

    When we log and run that, we get a new array of strings with both functions applied, and the code is significantly cleaner than the same operation would have been with the for loop.