DEV Community

Cover image for The JavaScript Array Map() Method
Sarah Chima
Sarah Chima

Posted on • Updated on

The JavaScript Array Map() Method

Ever wondered what the JavaScript array map method is? what it can do? or when it should be used? This is article is for you. Before we go any further, let us get a formal definition of the map method.

Meet the method

According to MDN documentation:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Let us simplify this.

The JavaScript map method takes an array(Array 1) and creates a new array(Array 2) by calling a function on each element in the given array(Array 1). To explain this further, we will use an example to see what the map method accomplishes.

Let us use our regular for-loop to show that the map function does. A classic example is if we want an array of the square of all elements in a given array, we could do this using a for-loop as seen in the example below:

    const array = [2, 5, 9];
    let squares = [];

    for (let i = 0; i < array.length; i++) {
        squares.push(array[i] * array[i]));
    }

    console.log(squares); // [4, 25, 81]
    console.log(array); // [2, 5, 9]

Enter fullscreen mode Exit fullscreen mode

What does the above achieve? It loops through an array, finds the square of each element in the array and pushes it to the squares array that was earlier defined.

This is similar to what the map function achieves only that you do not need to define another array that the result is pushed to. The map function automatically does that. So let us accomplish the above using the map function.

P.S: Arrow functions are used in the example. If you do not fully understand its syntax, please refer to this article on it.

    const array = [2, 5, 9];
    let squares = array.map((num) => num * num);

    console.log(squares); // [4, 25, 81]
    console.log(array); // [2, 5, 9]
Enter fullscreen mode Exit fullscreen mode

Notice how much easier it to use the map method and still accomplish the same thing. Also, note that the initial array remains the same, this is especially useful in functional programming. Now let us dig a little deeper into the map method.

The Map Method and its Syntax

The syntax of the map function is as follows:

    let newArray = array.map((currentValue, index, array) => {
        // return element to new Array
    });
Enter fullscreen mode Exit fullscreen mode
  • newArray - the array that is returned
  • array - the array on which the map method is called
  • currentValue - the value being processed
  • index - the index of the current value being processed
Here are some things to note about the map method:
  1. It returns a new array.
  2. It does not mutate the original array on which it was called i.e the original array stays the same.
  3. The range of element processed by the map function is set before the first invocation. If elements are added to the array after the map begins, it will not be processed by the callback.

When To use the Map Method

Given that there are other similar array methods like the ForEach method, you might wonder, "when should I use (or not) the map method?" Here are some questions that can help you decide:

  1. Do I need an array to be returned from the method and will the returned array be used?
  2. Am I returning a value from the callback function?

If your answer to any of these questions is Yes, you should use the map function. If your answer is negative in both cases, you should probably use forEach or for..of instead.

Examples of the Map Method

In addition to the example used before, here are some other examples of things you can do with the map method.

Example 1: Extracting values from an array of objects

We want to extract certain values from an array of objects. For instance, in a array of girls, we want to get the ages of the girls.

    const girls = [
       {name: 'Sarah', age: 19},
       {name: 'Laura', age: 10},
       {name: 'Jessy', age: 29},
       {name: 'Amy', age: 23}];

    let girlsAges = girls.map((girl) => girl.age);

    console.log(girlsAges);  //[19, 10, 29, 23]

Enter fullscreen mode Exit fullscreen mode
Example 2: Apply the Callback on only certain elements

If we want to the callback to only be applied to certain elements in an array, say odd numbers, we can use an if statement to do this.

    const numbers = [4, 9, 36, 49];

    let oddSquareRoots = numbers.map((num) => {
       if(num % 2 != 0) {
           return Math.sqrt(num)     
       }
       return num;
    })

    console.log(oddSquareRoots);
Enter fullscreen mode Exit fullscreen mode

or using ternary operators

    const numbers = [4, 9, 36, 49];

    let oddSquareRoots = numbers.map((num) => {
       return num % 2 !== 0 ? Math.sqrt(num) : num 
    })

    console.log(oddSquareRoots);
Enter fullscreen mode Exit fullscreen mode

However, a more efficient way to achieve this is using the JavaScript Array Filter method. This will be discussed in my next post.

Conclusion

The JavaScript Array Map method is a method that can be used to simplify your code if used correctly. If you have other examples to show how you use the map method, please share them in the comment section.

Got any question or addition? Please leave a comment.

Thank you for reading :)

Shameless Plug🙈

If you want to know more about me, here's a link to my website.

Top comments (19)

Collapse
 
sandordargo profile image
Sandor Dargo

Thanks for your article, the explanation is very clear.

On the other hand, I don't find the second example easy to grasp.

In modern programming, one of the most important principles is that elements should have names easy to understand and at the same time they should never lie about what their underlying structure does.

Let's have a look at it again:

const numbers = [4, 9, 36, 49];

let oddSquareRoots = numbers.map((num) => {
       if(num % 2 != 0) {
           return Math.sqrt(num)     
       }
       return num;
    })
Enter fullscreen mode Exit fullscreen mode

The map function returns a new list called oddSquareRoots. So what do I expect to have in it? It's very simple! Odd square roots! What do I get instead?

[4, 3, 36, 7]
Enter fullscreen mode Exit fullscreen mode

Those are not odd square roots! Those are some of the original numbers mixed with the square roots of some. Odd square roots apparently. Then I have a deeper look, I can figure out that actually, we have those original numbers that are even and the square roots of those that are odd. But that's not what the name says and that's something quite dangerous.

I don't work with JS a lot, so maybe there are different habits. Based on my experience, the example/use-case of applying a callback only on certain elements of a list is maybe a bit misleading.

Just like Python, JS also started to provide functional programming elements. Some of the main elements are map,filter and reduce. Each has its own very clear goal. I don't want to go into the very details, but in fact, they have very simple to understand names.

let oddSquareRoots = numbers.map((num) => {
       if(num % 2 != 0) {
           return Math.sqrt(num)     
       }
       return num;
    })
Enter fullscreen mode Exit fullscreen mode

In this case, map lies. What it does is filtering and then mapping some values and simply keeping some other values. Too many things in a map by an unnamed function.

If you want to get odd square roots, it's probably more readable to do it in two clear steps:

let oddSquareRoots = numbers.filter(num => num % 2 != 0).map(num => Math.sqrt(num));
let evenSquares = numbers.filter(num => num % 2 == 0);
console.log(oddSquareRoots.concat(evenSquares);
Enter fullscreen mode Exit fullscreen mode

If you need those numbers in their original order, maybe map is the only option, but the output's name still lies.

What do you think?

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you, Sandor, for pointing this out. That example was just to show that logic can be used in the map method. However, as you clearly pointed out, the filter method is a more efficient way of achieving that. In fact, my next post is on the filter method. I am going to update that example to add this point in order not to confuse anyone.

Collapse
 
daveskull81 profile image
dAVE Inden

Great article. Thanks for writing this. I can definitely suggest this to someone who is learning Javascript and has questions on how .map() functions. It's also nice for getting a refresher on how .map() works.

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you Dave

Collapse
 
lmuzquiz profile image
lmuzquiz • Edited
const array = [2, 5, 9];
let squares = [];

for (let i = 0; i < array.length; i++) {
    squares.push(array[i] * array[i]));
}

console.log(squares); // [4, 25, 81]
console.log(array); // [2, 5, 9]

On this code block you say that it: " ...finds the square of each element in the array..."

It would be more accurate to say that the relevant part of the code calculates (as opposed to finding) the square root of each element in the array.

Of course by the find, i think you meant "calculate" but then again, why not use the word calculate instead?

Collapse
 
boceto1 profile image
Jean Karlo Obando Ramos

Great article. Thanks for share this post with us.

Collapse
 
nickfazzpdx profile image
Nicholas Fazzolari

Great post. Very clear with sensible examples. The more I learn JavaScript the more I enjoy its power and short syntax.

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you Nicholas

Collapse
 
greatnonso7 profile image
Ichoku Great Chinonso

Thank you for this. I now understand how the map function works in js

Collapse
 
runosaduwa profile image
Runo-saduwa

Totally awesome!, I love this

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you Runo

Collapse
 
teexee19 profile image
Tochukwu Franklin Ene

Awesome one, map methods have never been explained any clearer than this to me before. Thanks a lot Sarah.

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you Frank

Collapse
 
rupeshiya profile image
Rupesh Krishna Jha

Hi,
Thanks for sharing .It's really awesome.
But I have one question that in angular2 + why we are using with http get ,post etc ?

Collapse
 
florensadi profile image
💎

Thanks Sarah. I understand better now.

Collapse
 
ruwanliyanage123 profile image
ruwan liyanage

Thank you very much for your article

Collapse
 
dougblackjr profile image
Doug Black

I was literally just thinking to myself, "I need to really understand how to use this." Thank you for explaining this!!!

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you for reading

Collapse
 
simplecarllos profile image
simple-carllos

Great post Sarah. I now clearly understand the map method. Can you blog about Javascript Events and their use in a map function on your next post?