Open In App
Related Articles

JavaScript Array map() Method

Improve Article
Improve
Save Article
Save
Like Article
Like

Javascript map() method creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally, the map() method is used to iterate over an array and call function on every element of the array. 

Syntax:

map((element, index, array) => { /* … */ })

Parameters:

  • element: It is a required parameter and it holds the value of the current element.
  • index: It is an optional parameter and it holds the index of the current element.
  • arr: It is an optional parameter and it holds the array.

Return Value:

It returns a new array and elements of arrays are the result of the callback function. 

Example 1: This example uses the array map() method and returns the square of the array element. 

Javascript




// Input array
let arr = [2, 5, 6, 3, 8, 9];
 
// Using map to transform elements
let newArr = arr.map(function (val, index) {
    return { key: index, value: val * val };
})
 
// Display output
console.log(newArr)


Output

[
  { key: 0, value: 4 },
  { key: 1, value: 25 },
  { key: 2, value: 36 },
  { key: 3, value: 9 },
  { key: 4, value: 64 },
  { key: 5, value: 81 }
]

Example 2: This example uses the array map() method to concatenate the character ‘A’ with every character of the name. 

Javascript




//Input string
let name = "Geeks";
 
// New array of character and names
// concatenated with 'A'
let newName = Array.prototype.map.call(name, function (item) {
    return item + 'A';
})
 
// Display output
console.log(newName)


Output

[ 'GA', 'eA', 'eA', 'kA', 'sA' ]

 Example 3: This example uses the array map() method to return the square of array elements. 

Javascript




// Map is being called directly on an array
// Arrow function is used
console.log([6, 7, 4, 5].map((val) => {
    return val * val;
}))


Output

[ 36, 49, 16, 25 ]

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 29 Nov, 2023
Like Article
Save Article
Similar Reads
Related Tutorials