Map

Map will loop through each item of array, same like forEach but Map returns the value of the array.

const arr = [{name:”James”,age:18}, {name:”Alice”,age:20}]

const person_names = arr.map(person => person.name)

console.log(person_names)

That will print

[“James”,”Alice”]

Easy? One of the biggest advantage to use Map over a old-school for loop is that you don’t hold temporary variable. Let’s do a reverse example for above code using for loop.

const arr = [{name:"James",age:18}, {name:"Alice",age:20}]

let temp = []

for(let i = 0; i < arr.length; i++){

temp.push(arr[i].name)

}

console.log(temp)

See? Map is no magic. Map significantly reduced the amount of code and avoided the use of variable holder.