Guide to JavaScript's map() Method

Introduction

Iterating through sequences can be used to access and display elements of the sequence - but more often than not, it's done to run an operation on each or some of the elements.

Note: Applying a function to each element of a sequence, and returning the transformed result into a new sequence is known as mapping, where each element of the original sequence, Ex, maps to a potentially transformed element of the new sequence, Exi.

Like most language, JavaScript has an efficient implementation of the map operation, and it's built into the Array class.

In this guide, you'll learn how to work with JavaScript's map() method and how it works, on practical code examples.

JavaScript's map() Method

Let's go through the for-loop syntax and see how we may apply certain methods to each element. Assume we have a set of scores and wish to add 5 points to each one to assist increase the scores:

const mathScores = [39, 50, 45, 41, 50]; 
let newScores = [];
  
for (let i = 0; i < mathScores.length; i++) {
    newScores.push(mathScores[i] + 5);
}

console.log(newScores); // [44,55,50,46,55]

In the code above, we looped through the mathScores array, adding 5 to each member, and then pushed the new scores to the newScores array.

This is a pretty standard procedure, and quite similar to what map() does!

The Array.map() method iterates across an array and applies a callback function on each element, returning the resulting elements in a new array.

Syntax

The syntax of the method is fairly straightforward:

const newArray = oldArray.map((currentValue, index, array)=>{
    // Do stuff with currentValue
})

The index and array are optional, and can be used to access the index of the currentValue and the original array itself.

  • newArray - The new array that is returned after the map() function has been applied.
  • oldArray - The map() function operates on the original array, and doesn't alter it.
  • currentValue - The value that the map() function is processing at step X, where the function defines what happens at step X.
  • index - The index of the current value.
  • array - An optional parameter that points to the original array.

For an intuitive visual experience - you can try logging these values and just returning the original one without any changes:

const mathScores = [39, 50, 45, 41, 50];
  
mathScores.map((currentValue, index, array) => {
    console.log('Current value:' + currentValue);
    console.log('Index:' + index);
    console.log('Array:' + array);
    return currentValue;
})
"Current value:39"
"Index:0"
"Array:39,50,45,41,50"
...
"Current value:50"
"Index:4"
"Array:39,50,45,41,50"

How Does map() Work?

The map() function, for all practical purposes, needs elements to work on - but if the array you're calling map() on is empty, it'll just return an empty array. It can be used with either arrow functions or regular functions:

Prior to ES6, you'd typically define a callback as:

const codes = [101, 201, 301, 303, 202];
let mathCodes = codes.map(function(code) {
    return `mth${code}`;
});
  
console.log(mathCodes); //["mth101","mth201","mth301","mth303","mth202"]

However, with ES6, you can use an arrow function to make the code cleaner:

const codes = [101, 201, 301, 303, 202]; 
let mathCodes = codes.map((code)=>{
    return `mth${code}`;
});
  
console.log(mathCodes); //["mth101","mth201","mth301","mth303","mth202"]

map() Examples

Let's take a look at a couple of examples of the map() function! For instance, let's calculate the square root of each number in the list:

const numbers = [9, 36, 64, 144];
  
let squareRoots = numbers.map((number) => {
    return Math.sqrt(number);
});
  
console.log(squareRoots); // [3,6,8,12]

Or, we could map each element to its length:

const names = ["Bilbo", "Gandalf", "Nazgul"];
let lengths = names.map((name) => name.length);
console.log(lengths); // [5,7,6]

Or, we could map each student object to their first and last names:

const students = [
    {firstName : "John", lastName: "Doe"},
    {firstName : "Stephen", lastName: "Matt"},
    {firstName : "Abigail", lastName: "Susu"}
];
  
let studentsNames = students.map(student => {
      return `${student.firstName} ${student.lastName}`;
})
  
console.log(studentsNames); // ["John Doe","Stephen Matt","Abigail Susu"]
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

One of the really commons use cases for the map() function on the front-end is to wrap data in HTML:

let cont = document.getElementById('#container');
  
let users = [
    { firstName : "John", lastName: "Doe", age: 17 },
    { firstName : "Stephen", lastName: "Matt", age: 16 },
    { firstName : "Abigail", lastName: "Susu", age: 15 }
];
  
let singleUser = users.map((user)=>{
    // Let's add the firstname and lastname together
    let fullName = user.firstName + ' ' + user.lastName;
    return `
      <h3 class='name'>${fullName}</h3>
      <p class="age">${user.age}</p>
    `
});
  
container.innerHTML = singleUser;

map() Vs Other Iterator Methods?

map() is an example of an iterator method in JavaScript, and it's very useful to understand when you'd want to utilize which iterator method. Iterator methods enable you to loop over all the objects in an array to perform specific operations.

When determining whether to utilize the map() function, it's a good idea to consider whether another iterator technique might be preferable.

Here are some of the additional iterator methods available in JavaScript:

  • reduce(): Reduction operations are one of the most powerful operations in functional programming, and typically involve reducing a vector to a scalar (a list of values, to a single one). This can be summing all values in an array, finding the average, minimum or maximum, or in any other way reducing a longer set of data to a smaller one, stemming from the original.
  • filter(): Filtering allows you to filter out the items from a list that do not fit some specific criteria and return an array of the remaining items that do.
  • forEach(): Similar to a for...loop, forEach() executes a function on each item in a list. It allows you to loop through an array and perform a job on each item.

To a degree - this begs the question:

What's the difference between map() and forEach()?

map() vs forEach()

Because both methods run through an array and are used to apply a function to each member, the map() and forEach() methods may appear extremely similar.

The main distinction between these two methods is that the map() function returns a new array, whilst the forEach() method does not - it alters the original array.

Additionally, in each iteration of the map() function, you'll return a transformed element. With forEach(), you don't return them, but can run functions on that change elements in-place. Though, you don't even have to run a function on the element!

This makes forEach() preferable when it comes to just, say, logging values, without changing them:

const characters = ['z', 'y', 'x', 'w'];
  
characters.forEach(character => {
    console.log(character);
});

Whereas, if you aim to change elements, map() is preferred.

Using map() With Other Array Methods

The map() method comes from functional programming - and with functional programming, chaining methods comes as natural as breathing. Chaining functional operations is extremely common, and can provide for very intricate operation pipelines!

Let's take a look at how you can chain map() with some other functional methods of the Array class.

Using map() with filter()

Filtering is usually the first operation in a pipeline, since it's inefficient to run operations on elements that might not be included in the result, unless the criteria by which you filter depends on some other operation in the pipeline.

A common sequence of steps is to filter() an array based on a certain criteria, and then map() the remaining elements.

Let's create an array of students to filter and map:

const mathStudents = [
    {
      name: 'Jane',
      score: 60,
      enrollmentYear: 2019
    },
    {
      name: 'Emmy',
      score: 40,
      enrollmentYear: 2020
    },
    {
      name: 'John',
      score: 43,
      enrollmentYear: 2019
    },
    {
      name: 'Linda',
      score: 20,
      enrollmentYear: 2019
    }
]

Now, let's filter the students based on their year - and get just the previous generation, and then map their scores,

We'll map the scores to a "passing"/"not passing" grade for a more human-readable format:

const passingStudents = mathStudents
    .filter((student) => student.enrollmentYear < 2020)
    .map((student) => {
      if (student.score > 40) {
        return student.name + ': passing'
      } else return student.name + ': not passing'
    });

console.log(passingStudents); // ["Jane: passing","John: passing","Linda: not passing"]

Using map() with reverse()

There may be times when you need to invert an array before or after executing other operations. This can be readily accomplished using the reverse() function:

const numbers = [21, 32, 43, 54, 65];
const newNumbers = numbers.map((number) => number * 2).reverse();
  
console.log(numbers); // [21,32,43,54,65]
console.log(newNumbers); // [130,108,86,64,42]

We've inserted the reverse() function at the end of the loop so that it reverses the resulting array. If we were to place the reverse() call before the map() call - we'd actually reverse the original array, and the map its elements, rather than reversing the new resulting array:

const numbers = [21, 32, 43, 54, 65];
const newNumbers = numbers.reverse().map((number) => number * 2);
  
console.log(numbers); // [65,54,43,32,21]
console.log(newNumbers); // [130,108,86,64,42]

Using map() on an Object

The map() function may also be used on objects after obtaining the values, keys, or key-values pair using the Object static methods (Object.keys(), Object.values(), and Object.entries()). Because each of these object static methods produces an array, map() may be simply chained to each:

const scores = { math: 50, English: 70, Physics: 45, Agric: 60 };  
let newScores = Object.values(scores).map((score) => score + 5);
  
console.log(newScores); // [55,75,50,65]

Conclusion

In this guide, we've taken a look at the map() method in JavaScript.

The method iterates through an array, applying a function to each element of the array and returning the new sequence of elements as a new array. We've taken a look at the syntax, parameters and usage of the method through practical examples.

Further - we've compared the map() method with the forEach() method, and explored how we can chain map() with filter(), reverse() and objects.

Last Updated: April 5th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms