JavaScript Array Map() Method

What the JavaScript array map method is? what it can do? or when it should be used?

According toMDN

Themap()method creates a new array with the results of calling a provided function on every element in the calling array.

A classic example is if we want an array of all elements in a given array multiplied by its square, we could do this using a for-loop as seen in the example below :


const array = [2, 5, 9];
let squares = [];
for (let i = 0; i < array.length; i++) {
  squares.push(array[i] * array[i]));
}
console.log(squares); // [4, 25, 81]

What does the above code do? It loops through an array, finds the square of each element in the array and pushes it to the new array as defined.
Now, Here MAP() comes into the role


const array = [2, 5, 9];
let squares = array.map((num) => num * num);

console.log(squares); // [4, 25, 81]

According to MDN .Map() Syntax

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])

callbackThe function that produces an element of the new Array, taking three arguments:currentValueThe current element is being processed in the array.indexoptional index of the current element being processed in the array.arrayoptional array wasmapcalled upon.

thisArgOptionalValue to use as whenthisexecuting.callback

Examples of the Map Method

Example 1: Extracting values from an array of objects

 const boys = [
       {name: \'Sarah\', age: 19},
       {name: \'Laura\', age: 10},
       {name: \'Jessy\', age: 29},
       {name: \'Amy\', age: 23}];

    let boysAges = boys.map((girl) => girl.age);

    console.log(boysAges);  //[19, 10, 29, 23]
Example 2: Apply the Callback on only certain elements

const numbers = [4, 9, 36, 49];

let oddSquareRoots = numbers.map((num) => {
  if(num % 2 != 0) {
    return Math.sqrt(num)     
  }
   return num;
})

console.log(oddSquareRoots);