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

Why do we start with var html=" "; ?

I don't understand the reasoning of starting with var html =" ";

1 Answer

Jamie Reardon
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jamie Reardon
Treehouse Project Reviewer

The reason why is because the variable is going to be a string variable that will be used in a loop. Since the variable is going to be a string, we can define it with an empty string value to begin with and add to the value within the loop each time the loop runs. If you were to define this variable inside of the loop the previous loop run where the value will be updated/added will be removed, this is because each time the loop runs, the value of html is being reassigned rather than updated. So when it gets to the end of the condition (which is i being 10), the actual value of html is 10.

You can test this yourself by placing the variable expression inside of the loop and printing to the page, you will see only one div being outputted with the value of 10.

Thanks!