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

Sam Weeks
Sam Weeks
Front End Web Development Techdegree Student 7,786 Points

trying to get my head around for loops

i was looking at the block of code that treehouse gave and i tried inputting it a different way i then couldnt figure out why it only output a single circle of 100 instead of 1-100 ive compared the two below..

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

var html =' ';
for(var i=1; i<=100; i+=1) {
var b = html + '<div>'+i+'</div>';
} document.write(b);

2 Answers

Adam Beer
Adam Beer
11,272 Points

What happens when you delete the first html variable? Like this:

for(var i=1; i<=100; i+=1) {
  var b =  '<div>'+i+'</div>';
} 
document.write(b);
Brenda Butler
Brenda Butler
Front End Web Development Techdegree Student 8,604 Points

Hi Sam.

I noticed that in the second version of the code you have two variables and the variable 'html' is never defined and is left as a blank string.

If you were to take out the html variable and run it as Adam stated above:

for(var i=1; i<=100; i+=1) {
  var b =  '<div>'+i+'</div>';
} 
document.write(b);

you are stating that the variable b has only one value, so the loop runs 100 times and then it gives you the ending value.

If you change it to this:

for (var i = 1; i<=100; i+=1) {
  var b;
  b+= '<div>' + i + '</div>'
}

document.write(b);

The variable b adds another value each time the code is run, as indicated by the +=. But if you run that code as above, you can see that the first time the loop runs the variable b is undefined, but then the second time it's run it has the first value of 1 which is added to the next time the loop runs and so on. You can avoid the first value of undefined if you declare the variable b as a string outside of the loop.

var b = '';
for (var i = 1; i<=100; i+=1) {
  b+= '<div>' + i + '</div>'
}
document.write(b);

Hope that helps!