Fireship · @fireship
Array Map in 100 Seconds
Uploaded December 17, 2019 · Length 1:41
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.
- 0:00
ArrayMap.
- 0:01
Create a new array by calling a function on every element in a different array.
- 0:05
Imagine we have an array of squares.
- 0:07
We can call a function on every single one of those squares using map to convert it to
- 0:11
a new array of circles.
- 0:13
In other words, it's just a loop, where the goal of that loop is to create a new array.
- 0:17
In our code, let's start with an array of objects that contain some user data.
- 0:21
Our goal is to take this array of objects and convert it to an array of strings that
- 0:25
only contain the user names.
- 0:27
We could do this imperatively by creating a new empty array, then use a for loop to push
- 0:31
each individual username to the new array.
- 0:33
Notice how we're using statements to change the app's state.
- 0:36
This is known as imperative programming.
- 0:38
Map on the other hand is declarative and describes how to create this new array using a function.
- 0:44
The new array is equal to the original array mapped to a function.
- 0:48
The function is passed as an argument to map, and it's called on every element in the original
- 0:52
array.
- 0:53
The function has access to the current element in the loop as well as its index.
- 0:57
In the body of the function, your job is to compute a new value and then return it.
- 1:01
And we've now solved the same problem we did with the for loop, but with less code
- 1:04
and without mutating the internal state.
- 1:06
If you're a ReactJS user, you'll often see Map used to take some initial data and then
- 1:11
map it to JSX for the actual UI.
- 1:13
Or maybe you need these usernames to do something asynchronously like fetch additional data from
- 1:17
the database.
- 1:18
You could do that by mapping them all to an array of promises, then running them concurrently
- 1:22
with promise.all.
- 1:24
One anti-pattern to be aware of with map is that you should only use it if you plan on
- 1:28
using the new array.
- 1:29
If you just need to run a loop, consider 4 each, or a regular 4 loop instead.
- 1:33
This has been ArrayMap in 100 seconds, thanks for watching, and I will see you in the next
- 1:38
one.


