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 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

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
Sara Masek
Front End Web Development Techdegree Student 11,218 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.