Skip to content

Instantly share code, notes, and snippets.

@lintonye
Last active May 8, 2018 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lintonye/80e9deb2d0cf8d55904a8d29dac3034f to your computer and use it in GitHub Desktop.
Save lintonye/80e9deb2d0cf8d55904a8d29dac3034f to your computer and use it in GitHub Desktop.
A really short lesson about Array.map()

There's a different way to loop through an array. I think it's pretty cool. For example:

['🍌', 'πŸ’', 'πŸ₯‘'].map(function(fruit) { return 'I like ' + fruit; })

Do you know what's going on here?

  • First of all, ['🍌', 'πŸ’', 'πŸ₯‘'] is an array of strings.
  • Second, .map() means it'll call the function map() but with the specific data in the array of fruits.
  • Third, the thing inside map() is a function, right?

This code will loop through the array of fruits, call the function with each fruit, and assemble the return values into a new array, in their respective order.

If you paste the code above into Chrome's console and press return, you'll get this:

['I like 🍌', 'I like πŸ’', 'I like πŸ₯‘']

This way of looping through an array is really useful in React. Take a mental note and we'll come back to it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment