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

Kevin Dunn
Kevin Dunn
6,623 Points

print() function not working properly

Hi,

I am having some problems with my print function.

I tried to print out the data by using the document.getElementById method, but it only prints out the last object in the array. In this case it would be Frank. How can I fix this?

var students = [
  { name: 'Kevin', track: 'Front End Development', achievements: 12, points: 3244},
  { name: 'Jimmy', track: 'iOS', achievements: 3, points: 544 },
  { name: 'Jane', track: 'Web Design', achievements: 50, points: 12244 },
  { name: 'Amy', track: 'Ruby on Rails', achievements: 20, points: 6244 },
  { name: 'Frank', track: 'Business', achievements: 2, points: 444 }
];

var msg;

function print(message){
  document.getElementById('output');
  output.innerHTML = message;
}

for (var student in students){
  msg = '<strong><p>Student: ' + students[student].name + '</p></strong>';
  msg += '<p>Track: ' + students[student].track + '</p>';
  msg += '<p>Points: ' + students[student].points + '</p>';
  msg += '<p>Achievements: ' + students[student].achievements + '</p>';
  print(msg);
}

Thanks

1 Answer

Steven Parker
Steven Parker
231,275 Points

:point_right: You may need a change to accumulate the student records.

Your loop calls the print function for each student. And your print function replaces the output text each time it is called. So together, they keep replacing the output so when the loop is done only the final student will be shown.

To change this, you'll want to change one or the other to accumulate (+=) rather than replace (=).

Kevin Dunn
Kevin Dunn
6,623 Points

Thanks! that worked