Unable to get a class method to work in loops

  javascript

I’m new to JS (or coding in general) and I’m experimenting with a few things to learn. I’m playing around with class methods in a loop for no reason other than to screw around and hopefully learn a thing or two, but I’m unable to get the desired result.

Here is the code:

class CD extends Media {
  constructor(title, artist) {
    super(title);
    this._artist = artist;
    this._songTitles = [];
  }
  get songTitles() {
    return this._songTitles;
  }
  addSong(song) {
    if (typeof song === 'string') {
      this._songTitles.push(song)
    } else {
      console.log('You need to input the song title as a string.');
    }
  }
  shuffle() {
  const songList = this.songTitles;
  const randomIndex = Math.floor(Math.random() * songList.length);
  return songList[randomIndex];
  }
};

const flowerBoy = new CD('Flower Boy', 'Tyler, The Creator');
flowerBoy.addSong('Foreword (feat. Rex Orange County)');
flowerBoy.addSong('Where This Flower Blooms (feat. Frank Ocean)');
flowerBoy.addSong('Sometimes...');
flowerBoy.addSong('See You Again (feat. Kali Uchis)');

const songs = flowerBoy.songTitles;
const randomIndex = Math.random(Math.floor() * songs.length);
while (flowerBoy.shuffle() != 'Sometimes...') {
  console.log(flowerBoy.songTitles[randomIndex]);
};

What I’m trying to achieve is a loop that’ll continue to shuffle through the flowerBoy.songTitles array until it comes across the string 'Sometimes...'. I think I’ve managed to achieve that because the output prints a different number of songs each time, but rather than printing the song names that I’ve pushed into the array, to the console, it replaces these strings to undefined.

Any help would be appreciated, thanks!

Source: Ask Javascript Questions

LEAVE A COMMENT