Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
How can I push a new Book object into empty array using Class syntax?

If a constructor in the class declaration already creates a book object, If i'm thinking about this correctly, all I would need to do is instantiate the object, then push that object into an array. What am I missing here?

class Book{
  constructor(title, author, pages, hasRead, library=[]){
    this.title = title
    this.author = author
    this.pages = pages
    this.hasRead = hasRead
    this.library = library
  }

  
addBookToLibrary(){
   return this.library.push();
 }
}

//instantiate Book Object
let newBook = new Book();

//push the object into the empty array??
newBook.addBookToLibrary("A book", "Charlie Morton", "500", true);


console.log(newBook.library);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As stated, originally you were not passing any arguments to your push method. If you are looking to create an array of arrays like:

[ [ "A book", "Charlie Morton", "500", true ], [ "Two book", "Charlie Morton", "200", false ] ]

Though I think an array of objects with key:value pairing would make it easier to use.

class Book{
  constructor(title, author, pages, hasRead, library=[]){
    this.title = title
    this.author = author
    this.pages = pages
    this.hasRead = hasRead
    this.library = library
  }
  
  addBookToLibrary(book){
     return this.library.push(book);
  }
}

//instantiate Book Object
const newBook = new Book();


//push the object into the empty array??
newBook.addBookToLibrary(["A book", "Charlie Morton", "500", true]);
newBook.addBookToLibrary(["Two book", "Charlie Morton", "200", false]);


console.log(newBook.library);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!