Table of contents
1.
Introduction 
2.
What is the map() method in arrays in JavaScript?
3.
Syntax of JavaScript Array map() Method
4.
Parameters of JavaScript Array map()Method
4.1.
function(currentValue, index, arr) 
5.
Return Value of JavaScript map() Method
6.
How to Use the Array map() Function in Java?
6.1.
JavaScript
6.2.
JavaScript
6.3.
JavaScript
7.
How to use the map() Function on an Array of Objects?
7.1.
JavaScript
8.
Examples of JavaScript Array map() Method 
8.1.
Example 1
8.2.
JavaScript
8.3.
Example 2
8.4.
JavaScript
9.
Mapping array elements using custom function
10.
Advantages of using Javascript map() Over for Loop
11.
Frequently Asked Questions
11.1.
How to use map () in JS?
11.2.
Can you use Array.map() to modify the original array?
11.3.
What are the different use cases for the map() method?
11.4.
What does new Map() do in JavaScript?
11.5.
Is a JavaScript Map a HashMap?
11.6.
Is JS Map faster than an Object?
12.
Conclusion
Last Updated: Dec 17, 2024
Medium

JavaScript Array map() method

Author Gunjan Batra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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 Javascript array map() method, 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

What is the map() method in arrays in JavaScript?

The map() method in JavaScript is used to create a new array by applying a callback function to each element of an existing array. It does not modify the original array but instead returns a transformed array. The callback function takes three arguments: the current element, its index, and the array itself.

Syntax of JavaScript Array map() Method

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.

Parameters of JavaScript Array map()Method

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.

  • Element- 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.

Return Value of JavaScript map() Method

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 Array map() Function in Java?

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 can also try this code with Online Javascript Compiler
Run Code

 

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);
You can also try this code with Online Javascript Compiler
Run Code

 

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);
You can also try this code with Online Javascript Compiler
Run Code

 

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);
You can also try this code with Online Javascript Compiler
Run Code

 

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

Examples of JavaScript Array map() Method 

Here are some examples of the map() function.

Example 1

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

  • 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);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

[50, 100, 48, 160]

Example 2

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

  • 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(" ");
}
You can also try this code with Online Javascript Compiler
Run Code

 

Output

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

Mapping array elements using custom function

  1. Create an empty array Arr .
  2. Iterate a loop through the array elements.
  3. Call function Func with the current element as the argument.
  4. Push the result of the Func function to the Arr array.
  5. Return the Arr array after going through all the elements.

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.

Frequently Asked Questions

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.

Can you use Array.map() to modify the original array?

No, Array.map() does not modify the original array. It creates a new array filled with values returned by the callback function applied to each element of the original array.

What are the different use cases for the map() method?

Use cases for map() include transforming array elements (like scaling numbers or changing string formatting), extracting data from an array of objects, and performing operations like converting strings to integers or formatting dates.

What does new Map() do in JavaScript?

The new Map() creates a Map object that stores key-value pairs, where keys can be of any data type and are guaranteed to be unique.

Is a JavaScript Map a HashMap?

Yes, JavaScript's Map is similar to a HashMap. It allows key-value storage with efficient lookup, insertion, and deletion, supporting any data type as keys.

Is JS Map faster than an Object?

Yes, a Map is often faster than an Object for frequent operations like lookups, insertions, or deletions, especially when keys are not strings or with larger datasets.

Refer to know about:   jquery ajax

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.

Live masterclass