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

131
Vistas
Can someone help me understand this JavaScript code

This code is used to add new books but I don't understand how it really works. I'm seeing a variable books used but was never assigned. How did it come to existence?

        <script>
            const bookManager = {
                addBook: function(book){
                    if(!this.books){
                        this.books = [book];
                    } else{
                        this.books.push(book);
                    }
                }
            };
        </script>
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

bookManager is an object. addBook is a method inside the object. The addBook method when called is checking if the bookManager object have a property called books. If it does not have the books then it is creating a books property in this line this.books = [book]; and adding book to it. If it has the property then it is pushing the book to it. Here this representing the object bookManager

const bookManager = {
  addBook: function(book) {
    if (!this.books) {
      this.books = [book];
    } else {
      this.books.push(book);
    }
  }
};

bookManager.addBook('test');
console.log(bookManager.books)

about 4 years ago · Juan Pablo Isaza Denunciar

0

this.books is initialized if it does not exist at: this.books=[book]. The check if it is empty is done in the if statement at: if(!this.books){}. It will be falsy the first time. If it exists, the next book will be pushed into the new array.

about 4 years ago · Juan Pablo Isaza Denunciar

0

The Manager object takes 'book' as argument and adds it to an array which is a property (similar to 'members' in other object-oriented languages). If the array doesn't exist, it creates one and initializes it with 'book' as the first element.

The usage would be

bookManager.addBook("The Swarm")

Result:

console.log(bookManager.books)

Array(1)
["The Swarm"]
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