The aim of this puzzle:
Use the .forEach()
array method to change the value of each item in an array.
Walkthrough of the solution:
The .forEach()
array method takes a function as an argument (also known as a callback function), and iterates through an array using each item as the argument for the callback.
The first line of code imports an array of objects from additional code, movieQueue
, so it can be used in this puzzle. Each object in movieQueue
has a title
and a hasWatched
property. The hasWatched
property of each item is false.
Next, the checkIfSeen
function is declared. It takes one argument, movie
, and prints its title
and hasWatched
properties to the console. This function is used as a callback in two .forEach()
methods later on in our code.
Below the checkIfSeen
function, the markAsWatched
function is declared. It takes one argument, movie
, and sets its hasWatched
property to true. We will use this function as an argument to a .forEach()
method that we will add to our code.
In this puzzle, you’ll use the .forEach()
method and the markAsWatched
function to change the hasWatched
property of the items in movieQueue
from false to true.
To complete the puzzle, add the .forEach(markAsWatched)
method after the movieQueue
that is alone on its own line. Now, all of the hasWatched
properties of the items in movieQueue
will be true. The preceding and trailing .forEach(checkIfSeen)
methods allow us to see that the hasWatched
property of each item has changed from false to true.
Sample code solution:
(Tap below to reveal)
import { movieQueue } from 'grasshopper.movies';
function checkIfSeen(movie) {
console.log('Watched ' + movie.title + ': ' + movie.hasWatched);
}
function markAsWatched(movie) {
movie.hasWatched = true;
}
movieQueue.forEach(checkIfSeen);
movieQueue.forEach(markAsWatched);
movieQueue.forEach(checkIfSeen);
JavaScript Concepts: Array Methods, .filter()
, Objects, Function Declarations, Imports
Additional Code (hidden code that runs before the puzzle’s code):
const movieQueue = [{
title: 'HopGun',
hasWatched: false
},
{
title: 'Hoppy Gilmore',
hasWatched: false
},
{
title: 'Mission Im-hop-ible',
hasWatched: false
}
];