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 trialTani Huang
6,952 PointsWhat 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
33,366 PointsHi 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:
time: listHTML = "<ul>" + "<li>" + arr[0] + "</li>"
time listHTML = "<ul>" + "<li>" + arr[0] + "</li>" + "<li>" + arr[1] + "</li>"
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:
time listLi = listLi = "<li>" + arr[0] + "</li>"
time listLi = "<li>" + arr[1] + "</li>"
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.
Tani Huang
6,952 PointsTani Huang
6,952 PointsThank you Heidi