Arrays and map
You'll learn to read and use map to transform a list.
map.Watch & read
Start with the required ones. The others are there when you need them.
See it step by step
Watch map turn each item into a new one.
Explanation
An array is a list of values in order. Very often you want a new list where every item has been changed in the same way: prices with tax added, names in capitals, users turned into labels on a screen.
map does exactly that. You give it a function, called a callback. map runs that function once for
each item, in order, and collects what the function returns into a brand new array.
Two things are always true. The new array has the same length as the old one, and the old array is not
changed. When you read list.map(x => …), ask yourself: what does one item become?
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1const words = ["hi", "yo"];2console.log(words.map(w => w.length));
doubleAll should return a new array with every number doubled. Fix the code so all three checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3What does
mapgive back? - 2 / 3What is
[10, 20].map(x => x / 10)? - 3 / 3In
nums.map(n => n + 1), which part is the callback?
Explain it back
How confident are you with Arrays and map?
Done
map call in React code.