Build a library project, method woes

I am trying to call the getAverageRating method in this project and I am getting this error

ReferenceError: rating is not defined
at Book.addRating (/home/ccuser/workspace/learn-javascript-classes-build-a-library/app.js:29:23)

I have removed the method to codepen and got it working as a standalone function on an array of values. I’m doing something wrong when I try to use it as a method, I’ve no clue where to go from here, can anyone give me a clue what i messed up?

Thankyou!

Edit: I have discovered my addRating() needed rating passed as an argument and I have correct that. If I log Ratings (the array) it now works, my getAverageRating method still htrows the same ‘ratings is not defined error’
.

class Media {

  constructor(title) {

    this._title = title;

    this._isCheckedOut = false;

    this._ratings = [];

  }

  get title() {

    return this._title;

  }

  get isCheckedOut() {

    return this._isCheckedOut;

  }

  set isCheckedOut(value) {

    this._isCheckedOut = value;

  }

  get ratings() {

    return this._ratings;

  }

  toggleCheckOutStatus() {

      this._isCheckedOut = !this._isCheckedOut;

    }

  addRating() {

    this.ratings.push(rating);

  } 

  getAverageRating() {

    var sum = 0;

    ratings.forEach(num => {

        sum += num;

    });

    return sum / ratings.length;

  }

}

  class Book extends Media {

    constructor(title, author, pages) {

      super(title);

      this._author = author;

      this._pages = pages;

    }

    get author() {

      return this._author;

    }

    get pages() {

      return this._pages;

    }

  }

  class Movie extends Media {

    constructor(title, director, runTime) {

      super(title);

      this._director = director;

      this._runTime = runTime;

    }

    get director() {

      return this._director;

    }

    get runTime() {

      return this._runTime;

    }

  }

  class CD extends Media {

    constructor(title, artist, tracks) {

      super(title);

      this._artist = artist;

    }

    get artist() {

      return this._artist;

    }

  }

const book1 = new Book('A Short History of Nearly Everything', 'Bill Bryson', 544);

console.log(book1);

book1.toggleCheckOutStatus();

console.log(book1.isCheckedOut);

book1.addRating(4);

book1.addRating(5);

book1.addRating(5);

console.log(book1.getAverageRating());

Hi @bilsner
compare how you addressed ratings in addRating() with how you did it in getAverageRating().

1 Like

Thankyou. It’s really easy to trip over the simple things.

1 Like