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

What is the difference between these two function ? (for loop)

//This is the correct answer
function listitem(arr) {
  listHTML = "<ul>";
    for (var i = 0 ; i < arr.length ; i += 1) {
    listHTML += "<li>" + arr[i] + "</li>";
  };
  listHTML += "</ul>";
  return listHTML;
};

//Eddit by myself
function listitem(arr) {
  for (var i = 0 ; i < arr.length ; i += 1) {
    listLi = "<li>" + arr[i] + "</li>";
  };
  listUl = "<ul>" + listLi + "</ul>";
  return listUl;
};

1 Answer

Heidi Puk Hermann
Heidi Puk Hermann
33,366 Points

Hi Tani,

In the first snippet you are appending an additional li element to the ul every time the for-loop has complete a step. If you ran it three times you would get the following:

  1. time: listHTML = "<ul>" + "<li>" + arr[0] + "</li>"

  2. time listHTML = "<ul>" + "<li>" + arr[0] + "</li>" + "<li>" + arr[1] + "</li>"

  3. time listHTML = "<ul>" + "<li>" + arr[0] + "</li>" + "<li>" + arr[1] + "</li>" + "<li>" + arr[2] + "</li>"

In the second snippet you are re-setting the value of your string, listLi every time you run the loop. The output would look like this, if you ran the loop three times:

  1. time listLi = listLi = "<li>" + arr[0] + "</li>"

  2. time listLi = "<li>" + arr[1] + "</li>"

  3. time listLi = "<li>" + arr[2] + "</li>"

In the end it comes down to wether you put += (append) or = (set) after the name of your variable.

Thank you Heidi