Reduce method - Bild a Library


#1

Hello!

I am doing the Bild a libreary project, but I stuck at Task 7. The reduce method returns undefined, although I get the correct average if I log it. Why is that? What is wrong?

class Media {
** constructor(title){**
** this._title = title;**
** this._isCheckedOut = false;**
** this._ratings = [];**
** }**
** get title() {**
** return this._title;**
** }**
** get isCheckedOut() {**
** return this._isCheckedOut;**
** }**
** get ratings() {**
** return this._ratings;**
** }**
** set isCheckedOut(newIsCheckedOut) {**
** this._isCheckedOut = newIsCheckedOut;**
** }**
** toggleCheckOutStatus() {**
** this._isCheckedOut = !this._isCheckedOut;**
** }**
** getAverageRating() {**
** let ratingsSum = this._ratings.reduce((currentSum, rating) => currentSum + rating, 0);**
** let lengthOfRatings = this._ratings.length;**
** let averageRatings = ratingsSum/ lengthOfRatings;**
** return averageRatings;**
** }**
** addRating(newRating) {**
** this._ratings.push(newRating);**
** }**
}

**//test: **
const vuk = new Media(‘Vuk’, false, []);
vuk.addRating(4);
vuk.addRating(2);
vuk.addRating(6);
vuk.addRating(8);
console.log(vuk);
console.log(vuk.ratingsSum);
console.log(vuk._ratings.length);
console.log(vuk.getAverageRating());

_Output: _
_Media { _title: ‘Vuk’, _isCheckedOut: false, ratings: [ 4, 2, 6, 8 ] }
undefined
4
5

Thank you for your help in advance!


#2

Please post your code with format:

How do I format code in my posts?

and without all the asterisks.


#3
class Media {
  constructor(title){
    this._title = title;
    this._isCheckedOut = false;
    this._ratings = [];
  }
  get title() {
    return this._title;
  }
  get isCheckedOut() {
    return this._isCheckedOut;
  }
  get ratings() {
    return this._ratings;
  }
  set isCheckedOut(newIsCheckedOut) {
    this._isCheckedOut = newIsCheckedOut;
  }
  toggleCheckOutStatus() {
    this._isCheckedOut = !this._isCheckedOut;
  }
  getAverageRating() {
   let ratingsSum = this._ratings.reduce((currentSum, rating) => currentSum + rating, 0);
   let lengthOfRatings = this._ratings.length;
   let averageRatings = ratingsSum/ lengthOfRatings;
    return averageRatings;
  }
 addRating(newRating) {
   this._ratings.push(newRating);
 }
}

//test: 
const vuk = new Media('Vuk', false, []);
vuk.addRating(4);
vuk.addRating(2);
vuk.addRating(6);
vuk.addRating(8);
console.log(vuk);
console.log(vuk.ratingsSum);
console.log(vuk._ratings.length);
console.log(vuk.getAverageRating());

Output:

Media { _title: ‘Vuk’, _isCheckedOut: false, _ratings: [ 4, 2, 6, 8 ] }
undefined
4
5


#4

the reduce method does not return undefined, console.log(vuk.ratingsSum); will give undefined but that has to do with variable scope, ratingsSum is a local variable, it only exist within the getAverageRating method