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

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,850 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.

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,850 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.