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 trialVince Shao
6,107 PointsWhy 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
kareem Pierre
Full Stack JavaScript Techdegree Student 20,263 PointsYou 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.
Unsubscribed User
3,120 PointsCould 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 +?
kareem Pierre
Full Stack JavaScript Techdegree Student 20,263 Pointsthe += 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.
Vince Shao
6,107 PointsVince Shao
6,107 PointsGot it!!! Thank you so much!!