JavaScript Looping Array elements

Can someone please explain each line of code to me, this lesson was supposed to be about arrays but there is looping in it, I haven’t reached the parts about loops yet.

var fruits, text, fLen, i;
fruits = [“Banana”, “Orange”, “Apple”, “Mango”];

//This is where I got lost//
fLen = fruits.length;

text = “<ul>”;
for (i = 0; i < fLen; i++) {
text += “<li>” + fruits[i] + “</li>”;
}
text += “</ul>”;

document.getElementById(“demo”).innerHTML = text;

var fruits, text, fLen, i; // declared variables
fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; // declare d array

//This is where I got lost//
fLen = fruits.length; // array length find

text = “<ul>”; //start creating unordered list dynamically
for (i = 0; i < fLen; i++) { // iterate until last array element
text += “<li>” + fruits[i] + “</li>”; // added li to ul
}
text += “</ul>”; //finaly close ul tag

document.getElementById(“demo”).innerHTML = text; //inserted list to inner html

1 Like

Ah thank you, makes much more sense. Could you explain this line a little more thoroughly?

text += “<li>” + fruits[i] + “</li>”; // added li to ul

Doesn’t text hold the <ul>? So does that mean we’re adding an <ul> right before the “<li>”? Little confuse with this line

Let’s clarify a little what’s going on:

fLen = fruits.length; // array length find

text = “<ul>”;

for (i = 0; i < fLen; i++) {
  text += “<li>” + fruits[i] + “</li>”;
}
text += “</ul>”;

Before we get into the for loop, we have a string that says <ul> and nothing else. On the first pass of the loop, we append to that string, so we now have <ul><li>Banana</li> and we reach the end of the loop, and go back to the start of the loop. Second pass, we add the next fruit (because i has incremented to 1): <ul><li><Banana</li><li>Orange</li>

We keep adding to the string, building it out as we go. By the end of that loop, the string looks like:

<ul><li>Banana</li><li>Orange</li><li>Apple</li><li>Mango</li>

And that’s great – but the ul still has to be closed. So, after the loop, close out that tag by adding </ul> to the very end of the string. This gives us

<ul><li>Banana</li><li>Orange</li><li>Apple</li><li>Mango</li></ul>

… and that is what gets inserted into the innerHTML of “#demo”.

1 Like

Ohhhhh, I completely understand now. Thank you for clarifying!