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 trialSereta Baldwin
6,183 PointsWhy does print() make undefined appear, where return doesn't?
I copied the following code from a previous lesson to use in my challenge solution:
function printList( list ) { var listHTML = '<ol>'; for ( var i = 0; i < list.length; i++ ) { listHTML += '<li>' + list[i] + '</li>'; } listHTML += '</ol>'; print(listHTML); }
However, as the teacher mentioned, we have to change it slightly for this challenge. When using the above code, everything worked fine, but 'undefined' was printed to the document after each list of correct/incorrect questions. When I changed 'print()' to 'return' (as in the video), 'undefined' went away.
I was just wondering why. Why was 'print()' the right thing to use in a previous lesson, but here you have to use 'return'?
Also, if any Treehouse Staff happen to be reading this, I'm really grateful for this slightly more challenging challenge. I thought everything had been a bit easy till now and I didn't feel like I was learning as much as I could've been. This feels like it's at the perfect level to get my brain working without me wanting to throw my computer out the window! :)
2 Answers
Steven Parker
231,275 PointsThe code that calls the "printList" function is expecting it to return a string, which it then puts on the page.
But when you "print" inside the function instead of returning anything, the code that called it gets "undefined" back as a result (which is then displayed).
So if you want to modify the function to do the printing directly, then where you call it you should remove the code that displays the result.
Sereta Baldwin
6,183 PointsOh I seeeeeeee. thank you! :)