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 trialEliana Haig
4,239 PointsMessage Printing Too Many Times
I can't figure out why my code is printing the objects in the array multiple times. What's wrong with my code? Guessing it's something to do with how I coded one of the loops. Thanks for your help! Here's the code. https://w.trhou.se/vo17pjzb0r
2 Answers
Pieter Bracke
4,078 PointsWhen you use the for (prop in students){} It is going to loop the complete var students times the number of students there are in the var students you don't really need it here ... I made a little codepen to show you the solution. I commented out the parts you don't need :)
Martin Zarate
10,723 PointsHere is a different approach to the loop:
var students = [
{ name: 'Luke',
track: 'iOS',
achievements: 5,
points: 2408
},
{ name: 'Juan',
track: 'Java',
achievements: 7,
points: 5455
},
{ name: 'Emily',
track: 'Front End',
achievements: 10,
points: 6799
},
{ name: 'Jason',
track: 'Full Stack',
achievements: 8,
points: 5432
},
{ name: 'Anne',
track: 'Ruby',
achievements: 11,
points: 8905
},
];
function print (message) {
var div = document.getElementById('output');
div.innerHTML = message;
}
var message = "";
// creates a counter to cycle through the list
for ( prop in students ) {
message += `
<div>
<h2>Student Info:</h2>
Name: ${students[prop].name} <br>
Track: ${students[prop].track} <br>
Achivements: ${students[prop].achievements} <br>
Points: ${students[prop].points}
</div>
`;
}
print(message);
Cheers.
Pieter Bracke
4,078 Pointsthat'll also do the trick :)
Eliana Haig
4,239 PointsThanks so much! As far as I can tell from my notes, I haven't encountered the notation of the $ in front of {} like you show. What is that called? I can't find it on MDN but then I don't know what to search for :-) Thanks!
Martin Zarate
10,723 PointsIt's called "template literal", it's a newer tech, so it's still not supported on all the browsers, only good browsers support it, meaning IE won't supported.
Eliana Haig
4,239 PointsEliana Haig
4,239 PointsThank you! I really appreciate it. I was wondering if I really needed that loop but I think I defaulted to it because it was one of the latest things I've learned.