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

Philip Kroupoderov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Philip Kroupoderov
Front End Web Development Techdegree Graduate 21,641 Points

Shouldn't the document.write be inside the for loop??

According to how I understand, the html variable is getting overwritten everytime the loop runs, so document.write should go right after html += '<div>' + i + '</div>'; in order to display the html value before it gets overwritten again and again.

According to the code: ...

var html = '';

for ( var i = 1; i <= 100; i += 1 ) { html += '<div>' + i + '</div>'; } document.write(html);

... document.write should only print the current value of html, which is 100 (it was overwritten 100 times). But since that's not the case, could someone please explain how exactly the loop is working??

3 Answers

This bit of code isn't overwriting the variable, instead it is adding to it (notice it says html += instead of html =)

 html += '<div>' + i + '</div>'; 

For example if we ran the loop 3 times the content of the variable would look like this:

<div>1</div><div>2</div><div>3</div>
laylazhang
laylazhang
5,111 Points

You are technically correct. The global variable is overwritten each time the loop runs. However, because of the "+=" operator, the global variable it not overwritten by just the new value i, it's overwritten by the previous value plus the new value. So eventually the html variable becomes:

<div>1</div><div>2</div>...<div>10</div>

You are also correct about the fact that the "document.write" can be placed inside the loop. The following bit of code works just the same as the example in the video.

for (var i = 1; i <= 10; i += 1) {
  document.write("<div>" + i + "</div>");
}
Janet Leon
Janet Leon
6,908 Points

Needed this as well! Thanks!