A simple guide to JavaScript Array Map Method

Aliyu AbubakarAliyu Abubakar
1 min read

Map is called on an existing array to return a new array based on what is returned from the function that’s passed as an argument.

Here is an example

const names = ['Bello', 'Abdullahi', 'Abdulqudus'];

const nameLengths = names.map( name => name.length );

Let’s take a look at what’s happening. The .map() method works on arrays, so we have to have declared our Array, to begin with:

// list of array 
const names = ['Bello', 'Abdullahi', 'Abdulqudus'];

We call .map()on thenamesarray and pass it a function as an argument.

names.map( name => name.length );

The arrow function that’s passed to.map()gets called for each item in thenamesarray! The arrow function receives the first name in the array, stores it in thenamevariable and returns its length. Then it does that again for the remaining two names.

.map()returns a new array with the values that are returned from the arrow function.

const nameLengths = names.map( name => name.length );

So nameLengthswill be a new array[5, 9, 10]. This is important to understand that the .map() method doesn't modify the original arrays, it only returns a new array.

0
Subscribe to my newsletter

Read articles from Aliyu Abubakar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aliyu Abubakar
Aliyu Abubakar

Software engineer with a passion for building user-friendly and visually appealing websites and applications. I have a strong foundation in blockchain technology and developer advocacy.