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 Object-Oriented JavaScript (2015) Constructor Functions and Prototypes Playlist Project

Tyler Anderson
Tyler Anderson
15,102 Points

Creating Previous button

I was messing with the entire project of playlist. However I was attempting to create a previous button for this playlist project. However I got some of it to work but not all of it. When I get to the top of the playlist and hit previous again it gives me the error play() and stop() undefined. I know there is a way to have the previous button work but not entirely sure how.

Playlist.prototype.next = function() {
  this.stop();
  this.nowPlayingIndex--;
  if(this.nowPlayingIndex === this.songs.length) {
    this.nowPlayingIndex = 0;
  }
  this.play();
};
Daniel Sokol
Daniel Sokol
14,888 Points

Since the nowPlayingIndex is decreasing, try changing the 'If' statement to:

if(this.nowPlayingIndex < 0) {
    this.nowPlayingIndex = ((this.songs.length)-1);
}

2 Answers

Steven Parker
Steven Parker
217,569 Points

Daniel's suggestion is good (but the parentheses are not necessary). Also, you might want to rename the function to match it's purpose, perhaps "last".

Personally, I prefer having the function not work at the ends rather than wrap around:

Playlist.prototype.last = function() {
  if (this.nowPlayingIndex > 0) {
    this.stop();
    this.nowPlayingIndex--;
    this.play();
  }
};

If you wanted to get really fancy, anytime the index changes you could check if it's at either limit and disable the appropriate button. Of course, if you're not at a limit you'd enable the buttons.

Tyler Anderson
Tyler Anderson
15,102 Points

Thank you Steven! this worked perfectly. however I like your comment about not having it work at the end! What and how would you do that? it it involve in removing the current playing class?

Hi, This is my solution to create Previous button:

Playlist.prototype.previous = function() { 
  this.stop();
  this.nowPlayingIndex--;
    if (this.nowPlayingIndex < 0) {      
      this.nowPlayingIndex = this.songs.length - 1;
      this.play();      
    } 
  this.play();
};