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

document.write inside for loop

How does this output a repetition amount of numbers

var html = ' ';

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

2 Answers

Steven Parker
Steven Parker
231,236 Points

I think you're asking why you get many more numbers than just 10, and that's because of the concatenating assignment operator "+=". This causes each step of the loop to print all the previous number again along with the new one.

To get the numbers to print just one at a time, use a normal assignment operator:

 html = "<div>" + i + "</div>";  // note "=" instead of "+="

The suggestion Kris made works in a different way. That method builds the string inside the loop but doesn't print anything until the loop is finished, then it prints all the numbers at once. But the final output would look the same.

Thanks Steven!!!

I'm not sure I understand the question but if you want to just list numbers 1 to 10 move the document.write statement outside the loop.

var html = ' ';

for(var i = 1; i <= 10; i++) {
 html += "<div>" + i + "</div>";
}

document.write(html);

Yea I understand that. I was just confused why my method wouldn't do the same thing.