Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda