How to map over an array in JavaScript
Published Mar 22 2022
The map() method in JavaScript iterates through an array, invoking a callback function upon each element and adding the returned value to a new array, which is then returned. Simple examples of when the map() method is useful include squaring each elements in an array of numbers or capitalizing the first letter of an array of strings. It is also commonly used in React for rendering an array of elements.
JavaScript array map examples
Code Playground
The .map() callback function arguments and arrays of objects
The callback function provided to .map() takes 3 arguments: the value of the current element, the index of the current element and the array upon which .map() was invoked. It is common only to require the first of these.
Just as we can map through arrays of strings or numbers, so too can we map through arrays of objects. This is a common requirement and is demonstrated in the code playground below.
Code Playground
Using map() and filter() together
The map() method can be used in conjunction with other array methods. This is called method chaining. map() is frequently used with filter(). Consider the example below where we want to find the number of Scottish football clubs over 100 years old.
Code Playground
As we have seen, the map() method in JavaScript runs every item in an array through a callback function and returns a new array with the values returned by the callback.
Far out, right!?