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

Loop question

Can someone explain to me about the document.write line?

If I am understanding it correctly, the document.write prints out the number but shouldn't it be within the { } since it prints out the number 10 times?

The way I read it is, if it is less than 10, the var html will add 1 to itself but then does the document.write code run and then go back to the for loop?

1 Answer

Cooper Runstein
Cooper Runstein
11,786 Points

The for loop adds a new string that will be an HTML element to the variable html each time it loops through the loop. Once the entire loop finishes, the document.write adds the contents of the html variable to the page.

var html = '' //html starts as an empty string
//First time through the loop is the same as:
html += '<div> 1 </div>' // now html = '<div> 1 </div>'
//Second time through the loop is the same as:
html += '<div> 2 </div>' //now html = '<div> 1 </div><div> 2 </div>'
//this continues until the condition in the for loop isn't true, and then:
document.write(html) //here the html has a string containing a div with each number between 1 and 10, and is added to the page

I hope that makes some sense. Instead of adding the HTML to the page on each iteration, it's appended to the variable html, and on completion, that variable is written to the page.

Chris Troy
Chris Troy
Full Stack JavaScript Techdegree Student 7,390 Points

So in other words, because var html is declared outside the loop, it does not need to be inside it. Correct?

Cooper Runstein
Cooper Runstein
11,786 Points

As in, you don't need to declare html inside the loop? If you were to do that, you would create an error because each iteration through the loop would attempt to declare the variable html again.