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

Sam Weeks
seal-mask
.a{fill-rule:evenodd;}techdegree
Sam Weeks
Front End Web Development Techdegree Student 16,699 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

Brenda Butler
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brenda Butler
Front End Web Development Techdegree Graduate 18,839 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!

Adam Beer
Adam Beer
11,314 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);