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

Shane Unger
Shane Unger
9,401 Points

My code works, and I think it's more flexible, I'd love some feedback!

var student;
var listHTML = '';

for (var i = 0; i < students.length; i++) {
    student = students[i];
    for (var key in student) {
        if (key === 'name') {
            listHTML += '<h2>Student: ' + student[key] + '</h2>';
        } else{
            listHTML += '<p>' + key + ': ' +  student[key] + '</p>';

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


I understand how Dave did it, but here it seems like if there are more properties added to the objects, like their age, city, etc., this code would be able to print that out without having to hardcode it in.

If I'm missing something, or could make this more efficient please let me know! Thanks in advance

1 Answer

Steven Parker
Steven Parker
230,248 Points

It's a bit of a trade-off in functionality.

The revised code will indeed list any other properties the elements may have.

But the original code would still list the names of any missing properties and show them as "undefined". The revised could would simply omit them entirely.

The choice to list only existing properties vs. every expected property would need to be made based on how the data were intended to be used and maintained. Now it is possible to accommodate both needs at the same time, but only with a good deal of additional code.

Shane Unger
Shane Unger
9,401 Points

I see what you're saying. So if one of the students didn't have an 'achievement' property listed for example my code would omit that, but if somehow it would be important to know that category was missing my code wouldn't alert you to that fact. That's something to consider, thanks for taking the time to review and respond!