On the Shelf explainer

Aim of the puzzle: Use the .push() array method to add an item to the end of the array.
Walk through of solution: The .push() array method is used to add a new item to the end of an array. In this puzzle, we will use it to add the object newBook to the end of the array bookShelf.

The first line of code imports the bookShelf array from additional code so that it can be used in this puzzle. This array contains two objects, each one containing the properties title and author.

The second line of code declares a new object, the variable newBook. Feel free to change the values of title and author.

On the third line of code, .push() is called on the bookShelf array, but has not been given an argument. To complete the puzzle, add newBook to the parentheses of bookShelf.push(), so that a new item can be added to the array.

The for…of loop at the bottom of the code will loop through the bookShelf array and print out the title and author of each book in the array. After adding newBook to the bookShelf array, run the code to see the new book printed to the console.

Feel free to add as many books as you like.

Sample code solution:

import { bookShelf } from 'grasshopper.books';

let newBook = {
    title: 'If Hemingway Wrote JavaScript',
    author: 'Angus Croll'
};

bookShelf.push(newBook);

for (let book of bookShelf) {
    console.log(book.title + ' by ' + book.author);
}

Javascript Concepts: Array Methods, .push(), Variable Declarations with Let, console.log(), For…of Loops, Objects, Strings
Additional Code (hidden code that runs before the puzzle’s code):

const bookShelf = [ {
    title: 'Gulliver\'s Travels',
    author: 'Jonathan Swift'
  },
  {
    title: 'A Room of One\'s Own',
    author: 'Virginia Woolf'
  }
];


3 Likes

Good explanation. Helped me understand better.

This needs to be updated to allow for solving it programmatically correct.