Search code examples
javascriptobjectpropertiesprototype

Function doesn't see Object property, but console.log does


I'm making a book library.

let myLibrary = []; //to store my Book Objects

function Book(title, author, onPage, totalPages) { //constructor function
  this.title = title;
  this.author = author;
  this.onPage = onPage;
  this.totalPages = totalPages;
  this.info = function() {
    return this;
  }
}

Now I made a function that will generate a Book object and will take user inputs as property values:

function addBookToLibrary() {
  let a = document.getElementById('bookTitle').value;
  let b = document.getElementById('authorName').value;
  let c = document.getElementById('onPage').value;
  let d = document.getElementById('numOfPages').value;
  myLibrary.push(new Book(a, b, c, d));
}

I make a function that will loop through the myLibrary array and sort them based on property values. For example:

function showBooks() {
  for (i = 0; i <= myLibrary.length; i++) {
    if (Number(myLibrary[i].onPage) < Number(myLibrary[i].totalPages)
      let newLi = document.createElement('li');
      newLi.innterText = myLibrary[i].title + ' by ' + myLibrary[i].author;
      inProgressBooks.prepend(newLi);
    }
  }
}

Now I will load my page and add an object using addBookToLibrary function. Now myLibrary[0].onPage returns a number that was taken from the input by addBookToLibrary. So why does function showBooks fail? It says it can not read onPage property of undefined.


Solution

  • As @ASDFGerte stated, your loop is wrong. If you use <=, you will run into the issue that the last entry will not exist.

    your array for examples has length 5, meaning the index from 0 to 4 is filled. If you start with i = 0, then the last index you try to adress will be 5 (array.length = 5). So if you want to use <=, you need to stop at array.length - 1.

    Or, like @ASDFGerte stated, just use < and the loop will stop at the last filled entry, because 4 < 5.