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!
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
Francis N10,376 Points
What is happening inside the function? I dont understand why we need a variable listHTML to equal to '<ol>'?
I also dont get how it causes JS interpreter to print out an ordered list. For example:
- I Did it My Way
- Imagine ....etc.
Can someone explain to me why and what is var listHTML = '<ol>' & listHTML += '</ol>'?
Joe Hartman20,881 Points
When Dave sets listHTML = '<ol>' he is simply declaring that there is now a variable called listHTML with an initial value of the string
(you'll also sometimes hear this called "initializing" a variable). This is the opening tag of the ordered list that we want to print to the screen. There's nothing magical about naming the variable, you can call it whatever you want, but it's best to use a name that's descriptive of what's contained in the variable.
You only need one opening tag for an ordered list to which you can add multiple list items. The loop is set up to generate those list items one-by-one each time through the loop using the items from the array already set up at the top of the page. The loop simply creates a list item (which is a string) containing the value from the array at each step of the loop. That string value is then added to the value of the variable on the left, that's where += comes in. += is a shorthand method of concatenating one string to another. It's the same as writing:
listHTML = listHTML + '<li>' + list[i] + '</li>';
The shorthand method saves you some time and makes your code a little leaner. As the loop runs, list items are added to the list until the number of items in the array is reached. Then the loop ends and the function executes the next step which adds the closing tag to the ordered list. The list is then all wrapped up nice and neat in the listHTML variable which is sent back to the calling function where it's sent to the browser to be printed out.
Hope this helps.