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

Vince Shao
Vince Shao
6,107 Points

Why my code is only printing the last object?

Here's my code, and it's only printing last object!!

Please tell me why!!

var students = [
  {
    name: "Vince", 
    track:"Graphic Design", 
    achievements: 5, 
    points: 2508
  },
  {
    name: "Bibi", 
    track:"Smile", 
    achievements: 9, 
    points: 8675
  }, 
  {
    name: "Banana", 
    track:"Sleep", 
    achievements: 4, 
    points: 0909
  },
  {
    name: "Amanda", 
    track:"Make Up", 
    achievements: 7, 
    points: 5453
  },
  {
    name: "Shao", 
    track:"Paint", 
    achievements: 1, 
    points: 7554
  }
];

var message = "";
var student;


function print(message) {
  var outputDiv = document.getElementById("output");
  outputDiv.innerHTML = message;
}


for ( var i = 0; i < students.length; i += 1) {
  student = students[i];
  message = "<h2>Student: " + student.name + "</h2>";
  message += "<p>Track: " + student.track + "</p>";
  message += "<p>Points: " + student.points + "</p>";
  message += "<p>Achievements: " + student.achievements + "</p>";
}
print(message);

2 Answers

You missed putting a plus in front of the first message. message += "<h2>Student: " + student.name + "</h2>"; Without the plus it just keeps resetting the variable to be the current running student and then gets overwritten when the loop runs again.

Vince Shao
Vince Shao
6,107 Points

Got it!!! Thank you so much!!

Could you explain why there needs to be a '+' in the '+=' for line 'message += "<h2>Students: " + students.name + "</h2>";? It is the first line for message. Why have a +?

the += is just another way of writing it. it is similar to writing it like student = student + student[i]; All it is doing is taking the current variable value and appending another value at the end of it.