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

Alaric Wimer
Alaric Wimer
7,940 Points

Why is the html variable even used at all?

I produced the same results as Dave with the following code:

for (var i = 1; i <= 10; i += 1) { document.write("<div>" + i + "</div>"); }

I'm curious as to the logic/reasoning behind using the html variable as Dave does in the video. Any help will be greatly appreciated!

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

I believe what you're referring to is a case where you start with a variable html and then are constantly building up the string and then using the document.write to write the whole thing at once. This means that only one write will happen to the document.

In your code, that write happens ten times. This might not be much of a performance hit now, but could potentially be a significant performance hit if you needed to have say 1000 divs (for some odd reason). Imagine that you're retrieving entries from a database and each result is a list item in a list. Then you loop over that list and write the item as a list item. That would be mean that you are reaching out and touching the DOM 1000 times instead of just once (assuming there were 1000 results to your query).

Hope this makes sense! :sparkles:

Alaric Wimer
Alaric Wimer
7,940 Points

Thank you Jennifer! That helps a lot.

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,252 Points

I'd have to see the video and the project for wider context but maybe it's a case of just showing us what HTML elements can be looped over when generating HTML code in a document. The HTML element only occurs once in a document so you don't need to loop that, so you'd only need to store it once in a document.

But I'm merely guessing about what it is your code needs to do. :-)