I need someone to explain to me certian JS code

<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;

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

document.getElementById("demo").innerHTML = text;
</script>

I don’t understand the way the text variable is used here.
Firstly, it’s set to <ul> and then in the loop it is changed to <ul> plus <li> and I don’t understand how that works since in HTML <ul> is used in the opening and closing of the list but here, every list item has it’s own <ul> tag

Second thing is that, text is set to be <ul></ul> and I don’t get it how can it be only </ul>

And what does fruits[i] do? What does it access

The "<ul>" and "</ul>" is outside of the for loop, so each one happens only once. Every item in fruits is put inside li tags, but there is only one ul element.

1 Like

How can <ul> be only outside the loop when there’s
for (i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; }
Doesn’t text += "<li> make <ul><li>?

The } marks the end of the loop. Only the code between { and } is the only code that repeats.

1 Like

I still don’t get it.
Inside the brackets there is text += "<li>", shouldn’t it make it <ul><li> since text variable is set to be “<ul>”?

The += is appending on to a single string. First text is "<ul>". Then in the first iteration of the loop it becomes "<ul><li>Banana</li>". In the second iteration of the loop it becomes "<ul><li>Banana</li><li>Orange</li>" and so on. After the loop has completed, "</ul>" gets added to the end.

2 Likes