Jump to content

Question regarding += assignment operator in for loop


RJL1
 Share

Recommended Posts

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>";

Hi, Im a beginner trying to learn some javascript code and I cant seem to wrap my head around this.
In the loop the text variable "<ul>" has "<li>" + fruits + "</li>" added to it becoming: text = "<ul>" + "<li>" + fruits + "</li">  inside the brackets.
Why isnt the "<ul>" looped 4 times like the rest of the code?

In my mind the output should be:
 

< "<ul>" + "<li>" + fruits[0] + "</li>";
"<ul>" + "<li>" + fruits[1] + "</li>";
"<ul>" + "<li>" + fruits[2] + "</li>";
"<ul>" + "<li>" + fruits[3] + "</li>";
"</ul>"

But it's not... Can someone explain? I hope it makes sense.
Thanks in advance

Link to comment
Share on other sites

Only the content inside the loop is repeated.

This is what the string looks like on each iteration of the loop:

text = "<ul>";
"<ul>"

text += "<li>" + fruits[i] + "</li>";
"<ul><li>Banana</li>"

text += "<li>" + fruits[i] + "</li>";
"<ul><li>Banana</li><li>Orange</li>"

text += "<li>" + fruits[i] + "</li>";
"<ul><li>Banana</li><li>Orange</li><li>Apple</li>"

text += "<li>" + fruits[i] + "</li>";
"<ul><li>Banana</li><li>Orange</li><li>Apple</li><li>Mango</li>"

text += "</ul>";
"<ul><li>Banana</li><li>Orange</li><li>Apple</li><li>Mango</li></ul>"

Since the string "<ul>" is not being appended inside the loop, it is not being repeated.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...