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 trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2 Solution

The 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!

var 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);

1 Answer

Steven Parker
Steven Parker
231,275 Points

The "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 ("+=").