Home > Software engineering >  Can someone help me understand this JavaScript code
Can someone help me understand this JavaScript code

Time:11-13

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>

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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.

CodePudding user response:

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"]

CodePudding user response:

bookManager is an object that contains a function called addBook. This function accepts a prop called book. this.books is creating a variable inside the function(addBook) that is only useable only in that function. There is also an if statement that adds book or books to this.books. If this.books is false then this.books will be an array of the given prop(book), and if this.books is true, then it will add the book to the this.books. Later, you can access the this.books that this is referring to the object name which is bookManager.

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

bookManager.addBook('Harry Potter');
console.log(bookManager.books);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Let's Check it step by step:

first you have a javascript object named bookManager.

const bookManager = {}

inside the object you have a function called addBook which takes book as a parameter.

inside the function, existence of this.books which this refers to addBook function is checked. in this code it's always going to be false so the code inside if (!this.books) {}

will always run and would assign an array with initial value of book to this.books. in this code example the else block would never run but if you modify your code to have this.books initialized early, like this :

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

bookManager.addBook('tast');

console.log(bookManager.books)

then the else block would run instead of if block and as now there already is a this.books, new book would be pushed with Array.push() method.

CodePudding user response:

Basically how this works step by step: First, we define the variable bookManager which is an object.

const bookManager = {}

Inside of the definition line there is this code:

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

Inside of the bookManager object we have an addBook function. Inside of the addBook function we can see that it basically does two things:

  1. It checks to see if bookManager (this) has a books value.
  2. If it does, then it uses Array.push() to add a new item to the end of the array (which is book)
  3. If not, then create a new array this.books with the first item being the parameter book.

Now you've noticed that there is now a new variable bookManager.books in the bookManager object. This is because when in the function we say this it means bookManager in this case. So that means that the line this.books means bookManager.books. The new variable this.books gets added to the bookManager object.

Now, to test this we can run the following code:

bookManager.addBook("hello, world");
console.log(bookManager.books);

In the console an array with the only item being "hello, world" will be logged.

  • Related