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
28,285 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