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

287
Views
How can I make this Javascript code more Dry?

This is for one of the assignments on Odin Project. As i'm testing things out, i'm realizing how this code is bad because it's not DRY. I would just be creating more and more book objects. How can I make this more clean?

let myLibrary = [];

    function Book(title, author, pages, hasRead){
      this.title = title;
      this.author = author; 
      this.page = pages;
      this.hasRead = hasRead;
    };
    
    function addBookToLibrary(newBook){
      return myLibrary.push(newBook)
    };
    
    let newBook = new Book("Wool", "Hugh Howey", "592", false);
    let lifeOfPi = new Book("Life of Pi", "Yann Martel", "392", false);
    
    addBookToLibrary(newBook);
    addBookToLibrary(lifeOfPi);
    console.log(myLibrary);

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

0

You could do something like this, so that you have a "BookLibrary" class.

// Make the class "BookLibrary"

var BookLibrary = function() { 

    
    this.myLibrary = [];


    this.addBookToLibrary = function(title, author, page, hasRead) {

        var newBook = {}; // a book new object to be stored to array

        newBook.title = title;
        newBook.author = author;
        newBook.page = page;
        newBook.hasRead = hasRead;

        this.myLibrary.push( newBook ); // add to collection of books

    }
    
}

// test demo

// instantiate the object 
var books = new BookLibrary();

// add some books
books.addBookToLibrary("Wool", "Hugh Howey", "592", false);
books.addBookToLibrary("Life of Pi", "Yann Martel", "392", false);

// see if it worked
console.log( books.myLibrary );

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!