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

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.