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

troy beckett
troy beckett
12,035 Points

.add();

I'm not sure what the .add() function doing here?

2 Answers

Grace Kelly
Grace Kelly
33,990 Points

Hi troy the .add() function simply adds a song to the playlist. However to do this there are a number of steps involved.

First off when you create the Song constructor function, you are giving it a list of properties that can be filled with values when creating an instance of the object:

function Song(title, artist, duration) {
  this.title = title;
  this.artist = artist;
  this.duration = duration;
  this.isPlaying = false;
}

When you create the Playlist constructor function, you add an empty array of songs that can be added to later on:

function Playlist() {
  this.songs = []; //empty array
  this.nowPlayingIndex = 0;
}

By adding the add method via using .prototype you are asking the program to add or push a song into the songs array:

Playlist.prototype.add = function(song) {
  this.songs.push(song); //add the song to the songs array
};

Then you are creating a new Playlist and Song object:

var playlist = new Playlist(); //create a new playlist

var hereComesTheSun = new Song ("Here Comes the Sun", "The Beatles", "2:54"); //title, artist, duration

The song and its details is then added to the playlist object via .add():

playlist.add(hereComesTheSun); //add the song "Here Comes The Sun" to the playlist

hope this helps!!

troy beckett
troy beckett
12,035 Points

Thanks for clearing that up.