JavaScript

Sadaf Partovi
seal-mask
.a{fill-rule:evenodd;}techdegree
Sadaf Partovi
Front End Web Development Techdegree Student 11,939 Points

addBook()?

the addBook() method has one parameter which is "book". Is this parameter the same as the Book class? In the library class, we have "books" and in the Book class we have Book with the capital "B", so where does this "book" in the addBook() method come from?? Thanks in advance:)

class Library { constructor() { this.books = []; this.patrons = [];

}

addBook(book) { this.books.push(book); }

addPatron(patron) { this.patrons.push(patron) } }

Paul Messmer
Paul Messmer
14,424 Points

What video is this regarding?

2 Answers

Peter Vann
Peter Vann
26,484 Points

Considering this code:

class Library {
    constructor(){
        this.books = [];
        this.patrons = [];
    }

    addBook(book) {
        this.books.push(book);

    addPatron(patron) {
        this.patrons.push(patron);
    }

const library = New Library();
const myBook = new Book('Harry Potter and the Sorcerer\'s Stone', 'J.K Rowling', '978-0439708180');
library.addBook(myBook);

'book' is the parameter passed into the 'library' instance's addBook function. Within that function, 'book' could be any word, but 'book' makes the most sense, in this context. 'myBook' is an instance of the Book class and is what is actually passed into the function at this line:

library.addBook(myBook);

Inside the function, 'myBook' is referenced as just 'book', because of how the function is declared.

Notice, also, that I changed

const book =

to

const myBook = 

in order to make the example more clear.

Peter Vann
Peter Vann
26,484 Points

To really prove it, save this code to a file:

class Book {
    constructor(title, author, isbn){
        this.title = title;
        this.author = author;
        this.isbn = isbn;
    }
}

class Library {
    constructor(){
        this.books = [];
        this.patrons = [];
    }

    addBook(book) {
        this.books.push(book);
    }

    addPatron(patron) {
        this.patrons.push(patron);
    }
}

const library = new Library();
const myBook = new Book('Harry Potter and the Sorcerer\'s Stone', 'J.K Rowling', '978-0439708180');
library.addBook(myBook);

console.log(library.books[0].title);

such as 'test.js' and then run it with

node test.js

from the terminal/command line (if you know how to use node.js) and it should log:

Harry Potter and the Sorcerer's Stone

or you can see it here: https://codepen.io/petrovnikov/pen/xxEQVJB