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

Function Song.prototype.toHTML, why there is a if inside that function?

I didn't understand that piece of code, why does need this:

if(this.isPlaying) { htmlString += 'class="current"'; }

Song.prototype.toHTML = function() { var htmlString = '<li'; if(this.isPlaying) { htmlString += 'class="current"'; } htmlString += '>' htmlString += this.title; htmlString += '-' htmlString += this.artist; htmlString += '<span class="duration">' htmlString += this.duration; htmlString += '</span></li>'; return htmlString; };

1 Answer

Maria Nygren
Maria Nygren
10,021 Points

Hi Gisele,

The if statement is checking whether or not this.isPlaying is set to true or false. If the song is currently playing then this.isPlaying will be true and it will enter the if statement where the class current gets added to the li as follows: htmlString += 'class="current"';
The htmlString will now contain : '<li class="current"' instead of just '<li'
If a song is not playing then this.isPlaying will be false and it will never enter the code that adds the class current to the li.

It is good to have a class only for the song that is currently playing so that it can by styled differently from the other list elements. All the rest of the list elements will not get the class="current" added to them since they are not playing and this.isPlaying will be false.

Thanks, there is another way to do that outside that function? I think it's weird put an if in the middle of concatenation.