Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
230,688 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();
};