Jump to content
Sign in to follow this  
RJL1

Question regarding += assignment operator in for loop

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

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...