Skip to main content

Command Palette

Search for a command to run...

A simple guide to JavaScript Array Map Method

Published
•1 min read•View as Markdown
A simple guide to JavaScript Array Map Method
A

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.

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.

More from this blog

Sadiqful

22 posts

A software developer who loves writing