JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to use the JavaScript Array map() method?

JavaScript array map() is one of the iteration methods that transform each element of the array by calling a callback function. The map() method does not modify the original array and returns the new array. The length of the newly created array is equal to that of the original array.

The map() method accepts a callback function that is called for each element of the array. When a callback function is called by the map() method, the current element being processed is passed to it as an argument. You modify the current element and return the updated value. These updated values become the elements of the new array.

function callback(element){
  console.log(element);
  return element + 4;
}

let numbers = [10, 20, 30, 40, 50];
let newArray = numbers.map(callback);
console.log(newArray);

Output

10
20
30
40
50
[14, 24, 34, 44, 54]

You can see that map() method is executed five times because the original array 'numbers' has 5 elements. In the callback function, 4 is added to each element, and an updated value is returned. Finally, the newArray is logged to the console.

Before the introduction of the map() method, for loop is used to perform the tasks, which are now done by the map() method.

let numbers = [10, 20, 30, 40, 50];
let newArray = [];
for(let i=0; i<numbers.length; i++){
  console.log(numbers[i]);
  newArray.push(numbers[i] + 4);
}
console.log(newArray);

What are the parameters passed to the callback function in the map() method?

In addition to the current element, the callback function accepts two other parameters, the index of the current element and the original array.

function callback(element, index, original){
  console.log(`Current element: ${element}`);
  console.log(`Current index: ${index}`);
  console.log(`Current element: ${original[index]}`);
  return element + 4;
}

let numbers = [10, 20, 30, 40, 50];
let newArray = numbers.map(callback);
console.log(newArray);

Output

"Current element: 10"
"Current index: 0"
"Current element: 10"
"Current element: 20"
"Current index: 1"
"Current element: 20"
"Current element: 30"
"Current index: 2"
"Current element: 30"
"Current element: 40"
"Current index: 3"
"Current element: 40"
"Current element: 50"
"Current index: 4"
"Current element: 50"
[14, 24, 34, 44, 54]

Arrow function in the map() method

It is recommended that you use the arrow function as a callback function. Let's rewrite the above code using the arrow function.

let numbers = [10, 20, 30, 40, 50];
let newArray = numbers.map((number)=>{
  return number + 4;
});
console.log(newArray);

You can even make the code more concise by removing parenthesis, braces and return.

let numbers = [10, 20, 30, 40, 50];
let newArray = numbers.map(number=>number + 4);
console.log(newArray);

Recommended Posts