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


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){
  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>';


1 Answer

Steven Parker
Steven Parker
200,775 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