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