Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

288
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda