Follow The New Tutorial updates on WhatsApp, Telegram or YouTube.

JavaScript array map() method

The JavaScript array map() method calls the specified function for every array element and returns the new array.

In this tutorial, you will learn how to use the JavaScript Array map() method.

JavaScript array map() method doesn’t change the original array.

map() creates a new array from calling a function for every array element.

map() calls a function once for each element in an array.

map() does not execute the function for empty elements.

Generally map() method is used to iterate over an array and calling function on every element of array.

Instead of manually iterating over the array using a loop, you can simply use the built-in Array.map() method.

Syntax

array.map(function(currentValue, index, arr), thisValue)
  • function(currentValue, index, arr): It is required parameter and it runs on each element of array. It contains three parameters which are listed below:
    • currentValue: It is required parameter and it holds the value of current element.
    • index: It is optional parameter and it holds the index of current element.
    • arr: It is optional parameter and it holds the array.
  • thisValue: It is optional parameter and used to hold the value of passed to the function.

Example

let arr = [3, 4, 5, 6];

let modifiedArr = arr.map(function(element){
    return element *3;
});

console.log(modifiedArr); // [9, 12, 15, 18]

The this argument will be used inside the callback function. By default, its value is undefined . 

Assigning number value to map() method this argument

let arr = [2, 3, 5, 7]

arr.map(function(element, index, array){
	console.log(this) // 80
}, 80);

Multiply all the values in an array with 10

const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)

function myFunction(num) {
  return num * 10;
}