javascript · level 2 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
builds a new array by changing every item.
.map() takes a function, runs it on every item, and collects each answer into a new array, in the same order. prices.map((price) => price * 2) doubles every price, and the old array stays as it was.
Notice that arrow function has no curly brackets and no return. When an arrow function is a single expression, it hands that value back by itself: an . Add curly brackets and you must write return yourself.
One item in, one item out: map always gives back an array of the same length.
const prices = [2, 5, 10];
const doubled = prices.map((price) => price * 2);
const labels = prices.map((price) => `£${price}.00`);
console.log(doubled);
console.log(labels);
console.log(prices); (price) => price * 2 does the same as (price) => { return price * 2; }, only shorter.
guess first
Two maps over the pets. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const pets = [{ name: "Rex", age: 3 }, { name: "Tibbles", age: 7 }];
const names = pets.map((pet) => pet.name);
const nextYear = pets.map((pet) => pet.age + 1);
console.log(names, nextYear, pets.length);
your turn
Your turn. Make every animal louder.
Fill in what each word should become. Use any text trick you like on word, such as word.toUpperCase() or a template literal. Press run.
fix it
The warmer temperatures come out as null. Fix it!
- Each item came out as
null, which is how the console shows a missing answer inside an array. Is anything handed back? - With curly brackets, an arrow function needs
return. Without them, it hands back the value by itself. - Remove the curly brackets and the semicolon inside them, so it reads (temp) => temp + 5, then press run.
nailed it
you changed every item in one line. :D
mapruns a function on every item and makes a new array.- A one-line arrow function hands back its value without
return. - With curly brackets, write
returnyourself.
new words in your collection
- map
- implicit return
This lesson isn’t saved. A free account remembers every lesson you finish.