JavaScript map() method

Many beginners in JavaScript tend to find it difficult on when to use the map(). But in this tutorial, we will be discussing the used case for this method with examples to better understand the concept.

map()

The map() method is used to iterate over an array and then return a new array with modified elements using a callback function. The callback function is executed on each element in the array.

Example: Multiplying all numbers in an array by 2.

using for loop:

let arr = [2, 4, 6, 8];

for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[i] * 2;
}

console.log(arr) 
// Output:[4, 8, 12, 16]

using map():

let arr = [2, 4, 6, 8]

let output = arr.map(function(num){
    return num * 2
  });

console.log(output) 
// output: [4, 8, 12, 16]

You can simplify the above code using arrow function:

let arr = [2, 4, 6, 8];
let output = arr.map(num => num * 2);

console.log(output) 
// output:[4, 8, 12, 16]

Iterating over an array of objects using map() method Example:

let names = [
    {firstname: 'Chosen', lastname: 'Vincent'},
    {firstname: 'Harry', lastname: 'Jones'},
    {firstname: 'Lee', lastname: 'Jack'}
]

let fullName = names.map(name => {
    return `${name.firstname} ${name.lastname}`
})

console.log(fullName) 
// Output: ['Chosen Vincent', 'Harry Jones', 'Lee Jack']

You can now see how easy it is to use the map() method other than for loop.