Three Pillars of JS
Exercise 1
This is an exercise to briefly practice the three pillars of JS: Types / Coercion, Scope / Closures, and this / Prototypes.
Instructions
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.Move the
addFavoriteBook(..)andprintFavoriteBooks()functions into theBookshelfclass as methods. Modify them so they use thethiskeyword to access thefavoriteBooksarray.Hint:
classmethods don't use thefunctionkeyword, just their name.Fill out the definition of the
loadBooks(..)function, which should receive an instance of theBookshelfclass that you will pass to it.loadBooks(..)should call the providedfakeAjax(..), usingBOOK_APIas 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 theBookshelfinstance passed toloadBooks(..). Then call theprintFavoriteBooks()method.Create an instance of
Bookshelfclass, and pass it as an argument toloadBooks(..).Hint: Class instantiation:
new Whatever().
class Bookshelf {
constructor() {
this.favoriteBooks = [];
}
// TODO: define methods `addFavoriteBook(..)`
// and `printFavoriteBooks()`
}
function addFavoriteBook(bookName) {
if (!bookName.includes("Great")) {
favoriteBooks.push(bookName);
}
}
function printFavoriteBooks() {
console.log(`Favorite Books: ${favoriteBooks.length}`);
for (let bookName of favoriteBooks) {
console.log(bookName);
}
}
function loadBooks( /* .. */ ) {
// TODO: call fakeAjax( .. );
}
var BOOK_API = "https://some.url/api";
// ***********************
// NOTE: don't modify this function at all
function fakeAjax(url,cb) {
setTimeout(function fakeLoadingDelay(){
cb([
"A Song of Ice and Fire",
"The Great Gatsby",
"Crime & Punishment",
"Great Expectations",
"You Don't Know JS"
]);
},500);
}
Primer
Primer.