Fireship · @fireship

Array Map in 100 Seconds

Uploaded December 17, 2019 · Length 1:41

Array Map in 100 Seconds

Summary

Learn how to use Array Map to create a new array by calling a function on every element in a different array, with examples in JavaScript.

  • array map
  • javascript array
  • functional programming
  • declarative programming
  • reactjs

Transcript preview

The first 2 minutes of the transcript. Select a timestamp to watch that moment on YouTube.

  1. 0:00

    ArrayMap.

  2. 0:01

    Create a new array by calling a function on every element in a different array.

  3. 0:05

    Imagine we have an array of squares.

  4. 0:07

    We can call a function on every single one of those squares using map to convert it to

  5. 0:11

    a new array of circles.

  6. 0:13

    In other words, it's just a loop, where the goal of that loop is to create a new array.

  7. 0:17

    In our code, let's start with an array of objects that contain some user data.

  8. 0:21

    Our goal is to take this array of objects and convert it to an array of strings that

  9. 0:25

    only contain the user names.

  10. 0:27

    We could do this imperatively by creating a new empty array, then use a for loop to push

  11. 0:31

    each individual username to the new array.

  12. 0:33

    Notice how we're using statements to change the app's state.

  13. 0:36

    This is known as imperative programming.

  14. 0:38

    Map on the other hand is declarative and describes how to create this new array using a function.

  15. 0:44

    The new array is equal to the original array mapped to a function.

  16. 0:48

    The function is passed as an argument to map, and it's called on every element in the original

  17. 0:52

    array.

  18. 0:53

    The function has access to the current element in the loop as well as its index.

  19. 0:57

    In the body of the function, your job is to compute a new value and then return it.

  20. 1:01

    And we've now solved the same problem we did with the for loop, but with less code

  21. 1:04

    and without mutating the internal state.

  22. 1:06

    If you're a ReactJS user, you'll often see Map used to take some initial data and then

  23. 1:11

    map it to JSX for the actual UI.

  24. 1:13

    Or maybe you need these usernames to do something asynchronously like fetch additional data from

  25. 1:17

    the database.

  26. 1:18

    You could do that by mapping them all to an array of promises, then running them concurrently

  27. 1:22

    with promise.all.

  28. 1:24

    One anti-pattern to be aware of with map is that you should only use it if you plan on

  29. 1:28

    using the new array.

  30. 1:29

    If you just need to run a loop, consider 4 each, or a regular 4 loop instead.

  31. 1:33

    This has been ArrayMap in 100 seconds, thanks for watching, and I will see you in the next

  32. 1:38

    one.