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 JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge

Enemuo Felix
Enemuo Felix
1,895 Points

Why html+= and not html = ?

I know += is used to increase count at each iteration but why did dave use it in this case

html+= 'div style='background-color: ' + rgbcolor + ' ''></div> ' ;

2 Answers

Hi again,

Usually, if you're trying to write in multiple html elements at one time or generate a whole code block, you build up the html code one piece at a time and then write it all to the document in one line. I believe in this example, there is a line where he writes the html variable into the html document.

The html += means that we're adding on to the existing html variable to generate the whole code block we actually want to add, piece by piece. If we used html =, it would overwrite what's already there and just set the html variable to that one line.

Does that make sense?

Enemuo Felix
Enemuo Felix
1,895 Points

Thanks Again. It does

html += is equivalent to html = html + "new content".

a.) var html = "cat";
b.) html = "dog";
c.) html += " dog";

a. console.log(html) // outputs the string, "cat"
b. console.log(html) // outputs the string, "dog"
c. console.log(html) // outputs the string, "cat dog"

// You will also see this used a lot when incrementing a variable.

x = 0;
x += 1;   // equivalent to x = x + 1;