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 trialMiguel Adan
Front End Web Development Techdegree Student 2,621 PointsThe Build an Object Challenge, Part 2 Solution Question Why can't I use the print() function outside of a loop?
In this lesson we use a for loop to print out records about students which is the easy part but when I try and use the "print()" function given to us outside of the loop it will only show whatever I last asked it to print instead of everything in the for loop and stuff outside the loop. Does that make sense? please help!
1 Answer
Steven Parker
231,248 PointsThe "print" function replaces the contents of the output div each time you call it. So it's normal for it to display only the last argument given to it.
But the loop was using it to print "message", which it kept expanding with more data each iteration by using the concatenating assignment operator ("+=
").
Miguel Adan
Front End Web Development Techdegree Student 2,621 PointsMiguel Adan
Front End Web Development Techdegree Student 2,621 Pointsvar message = ''; var student;
function print(message){ var outputDiv = document.getElementById('output'); outputDiv.innerHTML = message; }
var students=[ { Name:'Miguel', Track:'Front End', Achievment:'none', Points:2000, Age:29 }, { Name:'Jeka', Track:'back End', Achievment:'all', Points:9000, Age:31 },
{ Name:'Rossi', Track:'GP', Achievment:'champ', Points:25, Age:37} ]; for(var i = 0; i < students.length; i += 1){ student = students[i]; message += '<h2>Student: ' + student.Name + '</h2>'; message += '<p> Track: ' + student.Track + '</p>'; print(message); }*/
*IN THIS CODE THE RECORDS ALL CALLED ON WILL PRINT ONTO THE PAGE* *but when I add the following to the end of the code only the last portion is printed to the *page. WHY?!?
print(student.Points);