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

Henrique Machuca
Henrique Machuca
5,611 Points

Help to understand why the numbers get stacked!

Well, I would like to understand why does all the numbers appear when we write to the console!!

I thought that for each time that the loop happened, the variable HTML would get a new value and it would overwrite the previous one. I got a bit confused cause from previous classes I thought that the var took everything after the equal sign and assigned as its new value.

Can someone explain it to me please?!

The exercise is the following for those who donΒ΄t know:

var html = " ";

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

document.write(html);

2 Answers

Paul Stettnisch
Paul Stettnisch
10,712 Points

No, it doesn't overwrite the previous one. In you case document.write is being called 10 times. It may help to remember that the for loop is the same as writing: document.write(1) document.write(2) .. .. document.write(10)

Pretty much just calling the function 10 times. I hope this help ;)

I don't think you're calling document.write() 10x, since it is outside the loop, it's executed just once, what the loop is doing is adding each time one more <div>i</div> inside the html variable, this means after first loop there's just <div>1</div> stored after 2 loops <div>1</div><div>2</div> and so on, after ten loops you have it 10x inside the variable and you just print that to the screen, the magic does the "+=" after the html in the loop.