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
173,958 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!!!

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 49,922 Points

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.