Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialCharlie Bird
7,277 PointsAny idea why I'm getting 'undefined' before my ordered list?
Instead of using the createListItems function I used a couple of for loops in order to create the list items. However for some reason I get 'undefined' at the start, does anybody know why?
for ( let i = 0; i < correctQuestions.length; i++ ) {
correctQsList += `<li>${correctQuestions[i]}</li>`
}
for ( let i = 0; i < incorrectQuestions.length; i++ ) {
incorrectQsList += `<li>${incorrectQuestions[i]}</li>`
}
Tomas Schaffer
11,606 PointsHi Charlie,
You should post bigger picture of your code, because i dont see the topic.
Did you declare all variables? if yes are they not out of scope of this function?
Anyway i would create rather function for this case, it would be more correct solution.
1 Answer
Steven Parker
231,248 PointsI'd bet you forgot to initialize your variables as empty strings. Since the +=
operator adds to an existing string, if it has not been initialized the first item added will have "undefined" in front of it.
Using just the first loop as an example:
let correctQsList = ""; // first, initialize as empty string before using the += operator
// then the remaining code should work as expected
for ( let i = 0; i < correctQuestions.length; i++ ) {
correctQsList += `<li>${correctQuestions[i]}</li>`
}
Charlie Bird
7,277 PointsThank you Steven that was it!
I had initialized the variables but not as empty strings, now it makes sense why there is an 'undefined' getting added in. Changing them to empty strings gets rid of this.
Tomas Schaffer
11,606 PointsThere are already two answers with same solutions above, if this is issue then 4 variables are missing.
Juan Luna Ramirez
9,038 PointsJuan Luna Ramirez
9,038 Pointsdid you create variables for both
correctQsList
andincorrectQsList
?for example