JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

Karla Gallegos
Karla Gallegos
5,189 Points

listHtml += '</ol>';

function printList(arrayList) {
      var listHtml = '<ol>';
      for(i = 0; i < arrayList.length; i++) {
          listHTML += '<li>' + arrayList[i] + '</li>';
      }
listHtml += '</ol>';
print (listHtml)
  }

The part that I don't understand is when you do this below in side the printList function above.

listHTML += '</ol>';

If you do listHTML += '</ol>'

wouldn't that be '<ol>' += '</ol>' ??? I feel like listHTML += '</ol>'; is adding an extra '<ol> since listHTML is already being called after the for loop here... listHTML += '<li>' + arrayList[i] + '</li>';

So, I am not understanding that part. I know we are just trying to add the closing </ol> tag, but I don't undestand how its doing that in listHTML += '</ol>'; piece of code.

Also, what does += mean in that same piece of code? What am I not understanding?

Thanks!

1 Answer

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 48,726 Points

Assuming there were items in the array listHTML might look like this:

listHTML = '<ol>'
listHTML = listHTML +  '<li>Coffee</li>' = '<ol><li>Coffee</li>'
listHTML = listHTML +  '<li>Tea</li>' =  '<ol><li>Coffee</li><li>Tea</li>'
listHTML = listHTML +  '<li>Milk</li>' = '<ol><li>Coffee</li><li>Tea</li><li>Milk</li>'

The last assignment outside the loop like you said adds the closing tag

listHTML = listHTML +  '</ol>'  =  '<ol><li>Coffee</li><li>Tea</li><li>Milk</li></ol>'