DEV Community

Cover image for Javascript ES6 101: the map method
David Fox
David Fox

Posted on • Originally published at

Javascript ES6 101: the map method

The map method is a part of ES6 that is especially useful for React developers. What is it and how does it work? Let's take a look.

You can call on any array in your code to create a new array which is populated by 'mapping' each element in array1 to array2. What actually ends up in array2 is determined by the callback function you passed into the map method as an argument.

I love the below pseudo code that uses emojis to give a high-level visual representation of how map works. The initial array is mapped over with the 'cook' method to achieve the output array - cooked food!

[🐮,🐓,🥔].map(cook) => [🍔,🍗,🍟]
Enter fullscreen mode Exit fullscreen mode

So, how does this look using actual JavaScript code? In the simple example below, we are using the map method to create a new array with each element of the original array multiplied by two:

// Our array1 initialisation
const array1 = [1,4,9,16];

// array1 mapped over into a new variable called map1
const array2 = => x * 2);

// Outcome
array2 = [2,8,18,32]
Enter fullscreen mode Exit fullscreen mode

In practical terms, the map method is really useful in React, particularly for looping over an array inside JSX - it keeps your code really neat and saves you from having to call functions that exist outside of your JSX to do this.

Here's a snippet of that concept in action in a simple React twitter clone I built. The below is code from the 'TweetList' component which renders an individual tweet component for each tweet in the array

Callback functions in map accept the following arguments:

  • value - what we've seen so far
  • index - the array index of the array element you're currently on
  • array - the whole array

You can also pass an object to assign to the 'this' keyword after the callback function.

If you enjoyed this article, consider following me on twitter for more of the same kind of content

Top comments (0)