DEV Community

Cover image for JavaScript: How to use the .map() method
James Hooper
James Hooper

Posted on

JavaScript: How to use the .map() method

The map() method is used to create a new array.

In simple terms, a map is used to take an existing array and copy that array into a new one. In Web Development, it’s common you need to build out UI elements with JavaScript. The following demonstration will show you how to take some data from an array and create html markup and output the results.

We are going to create a button and add an ‘onclick’ method. The next step we need to take is creating a function named ‘moreFeatures()’. Now we will set it up so that we can output features of a product with the click of a button to display all product features in an unordered list.

Let’s look at this example and show you how to output an unordered list using the map() method.

Alt Text
This is the button the user will click to display the new array of features:
Alt Text
This is the output displayed as an html unordered list:
Alt Text

There are other approaches to outputting an array. You can loop through each item and push it to a string. However, the map() function is easy to use and makes it easier to create your html markup.

The map() method will actually return values and a new Array of the same size.

I like using the map() method because it is short and concise.

Top comments (0)