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

olu adesina
olu adesina
23,007 Points

how is the this.nowPlayingIndex= 0; working in the playlist consturctor function with the this is songs array

function Playlist() {
  this.songs=[];
  this.nowPlayingIndex= 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() {

};

2 Answers

Umy Ikem
Umy Ikem
21,383 Points

the nowPlayingIndex is an integer so it can be used as an index of an array to get an item in the array. Let's say you have an array

      var exampleArray = []; 
       exampleArray[nowPlayingIndex];
      //nowPlayingIndex is an integer - 0,1,2,3...exampleArray[2]

nowPlayingIndex is used to get the currently playing song in the songs array

Akash Sharma
seal-mask
.a{fill-rule:evenodd;}techdegree
Akash Sharma
Full Stack JavaScript Techdegree Student 14,147 Points

When you first start using the PlayList object functions that we made like play, stop and next the isNowPlaying value will take 0 (as defined from the constructor function) and so the first song object you called add on (from PlayList function/prototype) will be the song all these functions act upon.