This is an exercise to briefly practice the three pillars of JS: Types / Coercion, Scope / Closures, and this
/ Prototypes.
The code of this exercise can be executed via Node.js or in the console tab of your browser's developer tools.
-
In the
printFavoriteBooks()
function, make sure there's no accidental type conversion (ie, from number to string).Hint: Use
String(..)
to coerce something to a string type.
My Answer: In Favorite Books: ${ favoriteBooks }
, favoriteBooks
is implicity being converted from a string to a number, but making it explicit makes it that much more readable and clear what's happening there and unlikely to cause problems as the program becomes more complicated
-
Move the
addFavoriteBook(..)
andprintFavoriteBooks()
functions into theBookshelf
class as methods. Modify them so they use thethis
keyword to access thefavoriteBooks
array.Hint:
class
methods don't use thefunction
keyword, just their name. -
Fill out the definition of the
loadBooks(..)
function, which should receive an instance of theBookshelf
class that you will pass to it. -
loadBooks(..)
should call the providedfakeAjax(..)
, usingBOOK_API
as the URL and an inline function expression as the callback. -
The callback will be passed an array of book names. Loop through this array, passing each book name to the
addFavoriteBook(..)
method of theBookshelf
instance passed toloadBooks(..)
. Then call theprintFavoriteBooks()
method. -
Create an instance of
Bookshelf
class, and pass it as an argument toloadBooks(..)
.Hint: Class instantiation:
new Whatever()
.