bmjaczynski Posted December 13, 2020 Share Posted December 13, 2020 For this example: 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>"; why does the last line output as </ul> instead of <ul></ul>? Since it is using the += operator. Link to comment Share on other sites More sharing options...
JMRKER Posted December 14, 2020 Share Posted December 14, 2020 I don't see the problem. It appears to be working correctly. Add an alert(text) at the end to see results. What do you expect to see differently? Link to comment Share on other sites More sharing options...
bmjaczynski Posted December 14, 2020 Author Share Posted December 14, 2020 Yes it's correct code, but I'm new to coding so it seems my logic is flawed when I try to break it down and I'm not sure why. Why isn't the variable 'text' being looped since it's looping what looks to me like: for (i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; // "<ul>" = "<ul>" + "<li>" + fruits[i] + "</li>" } Same for the last line: text += "</ul>"; // "<ul>" = "<ul>" + "</ul>" Link to comment Share on other sites More sharing options...
dsonesuk Posted December 14, 2020 Share Posted December 14, 2020 It appends open ul, then the looping of li elements with array fruit values, and finishes with closed ul element at end after looping is finished. Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now