Update appNew update is available. Click here to update.
Last Updated: Sep 20, 2023
Medium

JavaScript Array map() method

Author Gunjan Batra
0 upvotes

Introduction

Sometimes we need to apply a function or operation on each element of an array to get a new array with modified values. This can be done by iterating over the array by the use of for() or forEach() loop. But there is another built-in function in JavaScript called array map() that can help you perform this type of operation gracefully without manually iterating over the array.

Using the array map function, you can perform these operations efficiently while maintaining the sanity of your code and avoiding writing the big loops. But the map() function can be a bit confusing if you are starting with your coding journey in javascript. 

javascript map function

If you want to know about the JavaScript Array map() method, then stay with me – here’s a detailed breakdown of the map function with its implementation.

What is the JavaScript map() Function?

The map() method creates a new array and fills them with the value obtained by applying the given function on each original array element. It is a non-mutating method, i.e., the map function does not change the original array elements. Instead, it creates and stores the value in a new array. The map function was introduced in javascript 5 (ECMAScript 5).

For example, you have an array of basic details about a group of persons, and you want to get each person’s name, then you can apply the map function.

Before starting the implementation, ensure you have node js runtime setup to run javascript programs on the terminal. If you are not having a node js runtime setup, you can choose any online compiler. There are plenty of online compilers available.

If you are using chrome, you can also run programs on the chrome developer tools console. You can access the chrome developers tools console by pressing Ctrl+shift+J (Windows) or  Ctrl+Option+J (Mac).

JavaScript map() Function Syntax

The syntax for the map() function is as follows:

array.map(function(currentValue, index, arr), thisValue)

The syntax of the map() contains two arguments – the callback function and this value.

Let’s discuss these arguments in detail.

JavaScript map() Parameters

function(currentValue, index, arr) 

This is the callback function that runs on each element of the given array, and the value returned by this function is stored in the new array. The callback function accepts the following arguments named currentValue, Index and arr. Let us look at what each of them means when we use this in and with the map function.

  • currentValue
    This holds the value of current elements being processed by the function. This is a required parameter.
     
  • Index
    This parameter holds the array index of the current element being processed by the function. This is an optional parameter.
     
  • arr
    This parameter holds the array on which the function is being called. This is an optional parameter.

thisValue

It stores the value to be used as “this” while executing the callback function. This is an optional argument. The default value of “thisValue” is undefined.

JavaScript map() Return Value

The map() function returns a new array containing the results of applying the callback function to each element of the given array.

How to Use the JavaScript map() Function?

Now we know the basics of the map function and its syntax in detail. We should start to implement the map function. To understand how to use the map() function, let’s consider an example:

Consider you have an array of the following elements:

let arr = [1, 2, 3, 4, 5];

And you want to multiply each element of the array by 2. You can implement this by the use of the map function as follows:

  • JavaScript

JavaScript

let arr = [1, 2, 3, 4, 5];
let temp = arr.map(function(element){
return element * 2;
})
console.log(temp);

 

You may implement the same by the use of a for loop as follows:

  • JavaScript

JavaScript

let arr = [1,2,3,4,5];
let temp = []
for(let i = 0; i < arr.length; i++){
temp.push(2 * arr[i]);
}
console.log(temp);

 

But, notice that you don’t need to create an empty array while using the map function, unlike the for loop method, where we need to create an empty array.

The code written using the map function is concise and easy to implement. We can write the same code even better by the use of the arrow (=>) function.

  • JavaScript

JavaScript

let arr = [1, 2, 3, 4, 5];
let temp = arr.map(element => element * 2);
console.log(temp);

 

Compare these three codes side by side, and you will notice how the map function can drastically cut down the length of code with the enhanced readability of the code. The map method also reduces the chances of error as we don’t need to declare and initialize the variables while using the map function. 

How to use the map() Function on an Array of Objects?

Suppose we are given an array of objects. The object encapsulates length and breadth as the fields to define the object as a rectangle. The array would look like this:

let rectangles=[{length: 10, breath: 5},
{length: 20, breath: 5},
{length: 12, breath: 4},
{length: 16, breath: 10}
];

You want to calculate the area of each rectangle. Then can you use the map() method to iterate over the array and get the area of rectangles by multiplying length and breadth? 

Yes, we can calculate the area of the rectangle by the use of the map() function. 

The value of the length and breadth of a rectangle can be accessed by using the key. Remember – A rectangle is an object!

  • JavaScript

JavaScript

let rectangles = [{length:10, breadth: 5},
{length: 20, breadth: 5},
{length: 12, breadth: 4},
{length: 16, breadth: 10}
];

let area = rectangles.map(function(rectangle){
return (rectangle.length) * (rectangle.breadth);
});

console.log(area);

 

Similarly, we can perform operations on an array of objects having more than two properties.

JavaScript Array map() Method Examples

Here are some examples of the map() function.

Example 1

Code in JavaScript

  • JavaScript

JavaScript

let rectangles = [{length:10, breadth: 5},
{length: 20, breadth: 5},
{length: 12, breadth: 4},
{length: 16, breadth: 10}
];

let area = rectangles.map(function(rectangle){
return (rectangle.length) * (rectangle.breadth);
});

console.log(area);

 

Output

[50, 100, 48, 160]

 

In the above code, we are using the map function on "rectangle" which has key value pair of length and breadth of different items. We are using the map function to calculate the area of each rectangle item.

Example 2

Code in JavaScript

  • JavaScript

JavaScript

const people = [
{firstname : "Ninja" , id: "1"},
{firstname : "Ninja" , id: "2"},
{firstname : "Ninja" , id: "3"}
];
people.map(getAll);
function getAll(item) {
return [item.firstname,item.id].join(" ");
}

 

Output

['Ninja 1', 'Ninja 2', 'Ninja 3']

 

In the above code, we are using the map function on "people" which has key value pair of names and ids of different people. We are using the map function to display the details of each person by concatenating the name and id present in the array.

Advantages of using Javascript map() Over for Loop

The advantages of using a map over loop are as follows:

  • Immutable: the map() function is immutable, i.e., your original array will remain intact. This is very useful if you need your original array elsewhere.
     
  • Cleaner code: the map function helps cut down unnecessary lines while writing code, thus helping you keep your code clean and more readable.
     
  • Quickness to code: the map function provides a quicker way to code than the conventional loops.

When not to use the map() function?

You should not use the map function if,

  • You are not using the array it returns.
     
  • You are not returning any value from the callback function

You should not use the map function in both of these cases. Instead, you should use for() or forEach() loop in such scenarios.

Frequently Asked Questions

What is map function in JavaScript?

map() in JavaScript is a function that creates a new array after computation on each element of the input array. It does not change the input array. No operation is executed if the array is empty.

How to use map () in JS?

Map function in javascript can be used by following the syntax of the function which is array.map(function_name(cur_value, i, array), this_value) where you need to define the function name with the appropriate parameters, and this_value is optional.

What is the map () function?

The map() function is a core concept in functional programming. It transforms each element of an array using a given function, producing a new array with the transformed values. This preserves the original array's immutability.

What is the function map in JavaScript ES6?

In JavaScript ES6, the map() function is an array method used to create a new array by applying a function to each element of an existing array. This function returns a new array with the transformed values.

Conclusion

This discussed the JavaScript Array map() method and how you can use this function with different types of arrays in javascript. We also briefly discussed the advantages of using the map function with some of its limitations.

You can refer to our Guided Paths to learn more about DSA, JavaScript, System Design, DBMS, etc. or you can take a look at the interview experiences of popular companies for placement preparations.

Do upvote our blog to help other ninjas grow. Happy Learning!

Previous article
JavaScript hasOwnProperty() Method
Next article
JavaScript parseint() Method