Javascript Map Function

#javascript

While working on javascript projects we come across numerous occasions where we have to work with arrays and list. Javascript map function helps us to iterate through them in a much cleaner and easy way.

Let’s consider a you have an array of the following elements

  const Ninjas = [
     { name: 'Naruto', age: 25, Village: 'Konohagakure' },
     { name: 'Gara', age: 28, Village: 'Sunagakure' },
     { name: 'Minato', age: 40, Village: 'Konohagakure' },
   ]

You realize you have to add a new property salary which 10 times their age, to each object in the array and put it into a new array. Well for this you need to iterate over the array.

Lets first do it using our old friend the for loop!

const newNinjas = [];
   for (let i = 0; i < ninjas.length; i++) {
     newNinjas[i] = { ...ninjas[i], salary: ninjas[i].age * 10 }
   }

Next let’s look at how to do using javascript map

 const newNinjas = ninjas.map(ninja => ({ ...ninja, salary: ninja.age * 10 }))

If you look at these two instantly you can see how cleaner using the map function is!. It just took us one line to do where it took about 3 lines using for loop. And unlike in the for loop we not keep incrementing i. Since map automatically pushes in to the array we not need to handle that part too.

Hope you guys start using javascript map function in your daily projects! Until next time Cheers!

All rights reserved 2020