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 Tracking Multiple Items with Arrays Using For Loops with Arrays

How come listHtml only returns the initial <ol> tag once if its in the for loop?

In the function printList();

The variable listHtml is first given the <ol> tag, then in the for loop within that function...

    for ( var i = 0; i < list.length; i++) {
        listHtml += "<li>" + list[i] + "</li>";
    }

So for each time this loop runs list.Html gets added an additional list item. I would think it would return a value like this.

<ol><li>....</li>
<ol><li>....</li>
<ol><li>....</li>
</ol>

Can anyone explain this to me? Please?

1 Answer

Don Hamilton III
Don Hamilton III
31,828 Points

Hey Freddie,

Your confusion is understandable.

The reason your output code isn't including a new ordered list tag to every list item is because you are adding content to your listHtml variable every time your loop iterates. Your += operator tells javaScript to add whatever code follows to the end of what is already stored in your variable.

So your variable being included in the for loop only references the variable in order to build on to it instead of repeating the code again.

Hope this helps!

Thanks for the explanation Don!

I think I get it now.