.map() method in javascript- Beginner guide

I ran into a challenge that required use of  .map(), .reduce() and .filter() methods. Previously, I have been tiptoeing around ES6 syntax. Why you ask? I found it a bit tough for me to understand.

I am going to share with you some of the things I learnt in this post.

What is map () in JavaScript?

.map() is a method in javascript that you can use to manipulate arrays in Javascript. The .map() method calls the function provided once for each element of the array.

The output of the map() method is another array. What the map method does is it takes the array and does something to each element of the array and them spits out the new array.

The map method itself has not changed the original array but makes a new array.

Lets look at an example.

let points = [1, 2, 3, 4, 5];
console.log(points);
// [1, 2, 3, 4, 5]

We have a simple array or numbers. We want to create a new array with the 10 points added to each array item.

let newPoints = points.map(function(num){ return num + 10});
// console.log(newPoints)
// [ 11, 12, 13, 14, 15]

As you can see, newPoints is an array.

We can make the function even more compact using ES6 syntax.

let newPoints = points.map( num => num + 10 );
// console.log(newPoints)
// [ 11, 12, 13, 14, 15]

Lets look at another example:
We have wizard each with a given allowance in their bank account.

let wizards = [{name: "Harry Potter", allowance:100}, {name:"Ron Weasley", allowance:50}, {name: "Hermione Granger", allowance:90}];

They have learnt of a magic spell that can double their allowance in the bank. Lets do this.

let tripleAllowance = wizards.map(money => money.allowance * 3);
console.log(tripleAllowance);
// [ 300, 150, 270 ];

NOTE:

  1. .map() does not create a new array, but you can assign its result to a variable.
  2. The array must have values otherwise, the map() function will not work.
  3. The map() method calls the provided function once for each element in an array, in order.

Leave a Reply

Your email address will not be published. Required fields are marked *