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
Savannah Lynn
13,662 PointsUnsure why my loop is not passing through all array objects
Hello,
I am using arrays, loops, and objects to display student data to the page. I set up a loop to run through each object in an array "students." For some reason, my loop only executes the function for the last object in my array, the student with the name "Harry". Any help? I am sure it is a type somewhere but I have exhausted all other typo-help resources. Thanks much!
var students = [
{ name: 'Matthew', track: 'Front-End Web Development', achievements: 2345, points: 45 },
{ name: 'Andrew', track: 'Back-End Web Development', achievements: 4567, points: 78 },
{ name: 'Damian' , track: 'iOS Development', achievements: 5678, points: 45 },
{ name: 'Savannah' , track: 'Ruby', achievements: 3456, points: 35 },
{ name: 'Harry' , track: 'Python', achievements: 3456, points: 35 }
];
var html = '';
function print(message) {
var div = document.getElementById('output');
div.innerHTML = message;
}
for (var i = 0; i < students.length; i += 1) {
html = '<h2> Name: ' + students[i].name + '</h2>';
html += '<li>Track: ' + students[i].track + '</li>';
html += '<li>Achievements: ' + students[i].achievements + '</li>';
html += '<li>Points: ' + students[i].points + '</li>';
}
print(html);
2 Answers
andren
28,558 PointsYour loop is running through all of the students, the fault comes from this line:
html = '<h2> Name: ' + students[i].name + '</h2>';
You use the = operator instead of +=. = will replace the contents of the variable entirely with the value you provide while += will simply add the value provided to the variable. This means that at the start of each loop cycle you are erasing everything that was currently stored in the variable and replacing it with the string you provide. Since the other lines uses += those are added correctly.
If you fix that typo by using the += operator then your code should work.
Savannah Lynn
13,662 PointsThanks much!