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
Russell Wright
Courses Plus Student 4,354 PointsI used a 'for in' loop but the solution didn't. Did I do it wrong?
I completed the challenge successfully using a 'for in' loop but the solution video showed a simple for loop which counted through the object properties, the same as previous challenges. I assumed I would be required to use the new 'for in' loop that I was just taught.
My code:
var message = '';
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
for (var prop in students) {
message += ("<h2>Student: " + students[prop].name + "</h2>");
message += ("<p> Track: " + students[prop].track);
message += ("<br> Points: " + students[prop].points);
message += ("<br>Achievements: " + students[prop].achievements);
}
print(message);
Instructor code using the same object array:
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);
I don't see that my code is any less efficient but I'm new to this so it might not be obvious. Please let me know if there is good reason to write it how the instructor did.
Thanks for your advice.
1 Answer
Julian French
3,257 PointsIdeally as long as the code works, everything is fine, especially in the real world. I think the exercise was made to specifically test for the for loop so that's probably why it was marked the way it was.