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

129
Views
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 answers
Answer question

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 Report

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 Report

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 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!