Map()

Gabriel Castro
2 min readMay 1, 2021

Lets talk Map method. This method is invaluable when it comes to iterating over an array to get your desired result. The map() method creates a new array that is populated with the results of the provided function on every element in the calling array.

Examples

Alright, now we get the gist of what it is….lets take a look at a couple examples that make this method so useful!

const numArray = [2, 4, 6, 8];//function call
const numMap = numArray.map(x => x + 4);
//return callconsole.log(numMap);
//[ 6, 8, 10, 12 ]

This is a pretty minimal example of what we can do with Map(). Here we are simply setting a variable to an array of numbers, then we set a new variable equal to our numArray. From there we can simply add .map to the end where we can run what we want our output to be. In this case using addition to return the follow [6,8,10,12].

Lets look at another example, one where we can iterate over a unicode decimal code to return as many as we need, in this case we will return 5 stars to create a rating template.

import React from 'react';export default function App() {//setting up our .map on an array
const StarRating = () => {
return (
<div className="star-rating">
{[...Array(5)].map((star, index) => {
index += 1;
return (<button>
<span className="empty-star">&#9733;</span>
</button>
);
})}
</div>
);
};
//returning our unicode decimal code, in this case 5 timesreturn (
<div className="App">
<StarRating />
</div>
)
};

Ok, lets look at this.. the great the about map() method is that its the same from JavaScript to React. Here we have our basic React component, in this case however we are using the spread operator to take in the value of what we are returning each time from our array. We are then mapping over our array 5 times and each time our index increases, we add one star.

Voilà!

From here we can add functionality, such as allowing users to click on a star and have all stars up to the point be filled in.

Happy Coding!

--

--

Gabriel Castro

Full Stack, Software Engineer. Focus in Rails, JavaScript and React.