Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Lauren Namba
Lauren Namba
4,576 Points

"Cannot read property 'play' of undefined"

Hi,

I keep receiving the same error in my console. It says there is a problem with my playlist.js file on line 12, but I can't seem to find what I am doing wrong. Thanks for your help!

function Playlist() {
  this.songs = [];
  this.nowPlaying = 0;
}

Playlist.prototype.add = function(song) {
  this.songs.push(song);
};

Playlist.prototype.play = function() {
  var currentSong = this.songs[this.nowPlayingIndex];
  currentSong.play();

};

Playlist.prototype.stop = function(){
  var currentSong = this.songs[this.nowPlayingIndex];
  currentSong.stop();
};

Playlist.prototype.next = function() {
  this.stop();
  this.nowPlayingIndex++;
  if(this.nowPlayingIndex === this.songs.length){
    this.nowPlayingIndex = 0;
  }
  this.play();
};

Playlist.prototype.renderInElement = function(list) {
  list.innerHTML = "";
  for(var i = 0; i < this.songs.length; i++){
    list.innerHTML += this.songs[i].toHTML();
  }
};

2 Answers

Steven Parker
Steven Parker
215,939 Points

There doesn't seem to be enough code here to replicate the issue. You can share everything at once if you make a snapshot of your workspace and post the link to it here.

In the meantime, I was wondering if line 3 should actually be: "this.nowPlayingIndex = 0;" instead of "this.nowPlaying = 0;"?

Lauren Namba
Lauren Namba
4,576 Points

Hi Steven,

Thanks for your response! I was ready to take the snapshot and just tried changing the "this.nowPlaying = 0;" to "this.nowPlayingIndex = 0 and it did the trick! And of course it makes sense to me now! Thank you again for your help!