JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops For Loops

Philip Kroupoderov
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,902 Points

Needed this as well! Thanks!