Follow the Map explainer

The aim of this puzzle: Complete the arrow function so that it takes an item and returns its price.

Walkthrough of the solution: The groceries variable is an array of objects. Each object has a .name and .price property. To get an array with just the names, .map() and an arrow function are used. .map() is similar to .forEach() except it creates a new array instead of changing the original array.

To get an array of just the price values, we want to .map() each item to its price. We can make an arrow function that does that. It will use item as an input parameter between its parentheses (). Then inside the curly brackets {}, it should return item.price.

That whole arrow function is the argument of the .map() method. The .map() will run each element of the groceries array through that function and then return a new array of all the results. That new array gets stored inside of the prices variable so we can log it to the console.

Sample code solution:
(Tap below to reveal)

import { groceries } from '';

let names = => {
let prices = => {
  return item.price;

console.log('Names: ' + names);
console.log('Prices: ' + prices);

JavaScript Concepts: Code Block (arrow function), console.log(), .map()
Additional Code (hidden code that runs before the puzzle’s code):

let groceries = [
    {name: 'Grasshopper Gumdrops', price: 4},
    {name: 'Bug Juice', price: 8},
    {name: 'NaN-grain Bread', price: 15},
    {name: 'Bookworms', price: 16},
    {name: 'Nulled Cider', price: 23},
    {name: 'pop() Corn', price: 42}
1 Like

When I went to add ITEM between the parentheses, it wasn’t coming up as an option (see screenshot). Only after getting an error was I allowed to manually type it in, rather than the usual button selection.

This is Roscoe McKinley I am.

Hi can someone give me a practical example of the difference between .map, .foreach and loops?
Especially this part sounds similar to a loop to me:

Thank you

Hey there, great question!

You’ve definitely caught on that these methods are often used in place of loops. For example, take a look at the following 2 blocks of code:

let nums = [1, 2, 3, 4];
let doubledNums = [];
for (let num of nums) {
    doubledNums.push(num * 2);
let nums = [1, 2, 3, 4];
let doubledNums = => num * 2);

Both code blocks do the exact same thing, but using .map() means you can do it in 2 lines, without sacrificing readability (in fact, I’d argue that it looks even more readable than a for loop).

Hope this explains things! Let me know if you have any questions.

It’s more readable indeed!

And I guess .forEach makes it simpler when it comes to callback functions, because it avoids the for (let num of numbers) part.