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 Working with 'for' Loops Dynamically Display HTML with a Loop

html += `<div>${i}</div> logic behind +=?

I was able to complete the for loop without problem, however I'm quite thick in the head and couldn't grasp the logic behind the "+=" in html += <div>${i}</div>

I know that "+=" produces ${i} from zero to ten, and a "=" only prints out a number ten, but I just can't wrap my head around it.

It'll be awesome if someone could tell me how this logic translates to easy words

2 Answers

Bramyn Payne
Bramyn Payne
19,589 Points

html is initialized as an empty string. Each time through the for loop, the += operator adds the new string element. The += operator is just a shorthand way to write it.

html += <div>${i}</div>;

Would be the same as:

html = html + <div>${i}</div>;

So each time through the for loop, the html variable is updated by concatenating the old html string with a new string.

Hopefully this makes a little more sense!

I think the part where I don't understand is that: which part of the code allows the "html" before addition to be logged, and not disappear after the addition is complete, like the result with "html = html....".

hope this makes sense.

Sara Masek
seal-mask
.a{fill-rule:evenodd;}techdegree
Sara Masek
Front End Web Development Techdegree Student 11,513 Points

hey Chun, it was kind of confusing to me too but I think what the html variable represents is just an initialized placeholder to hold the div elements; in other words, it's like an empty shell that has to be filled with a value (in this case the divs containing the value of "i").

Also, I think using "html" as a variable might have led to confusion. When I see html I immediately look at it as an object to manipulate the DOM rather than an empty variable, which is what this video set it to.

Hope that helps.

rashid sabag
rashid sabag
4,647 Points

very helpful thanks