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

Why can't you just loop through and print both the key and value at the same time?

It seems like logically you should be able to just loop through both the object key and value (using dot notation) at the same time instead of having to write out the "student.property" statements. Something like:

for (var i = 0; i <= students.length; i +=1) { var student = students[i]; for (var prop in student) { document.write("<p>", prop, ": ", prop.prop, "</p>"); } };

2 Answers

Steven Parker
Steven Parker
231,236 Points

You can't use dot notation there because "prop" is not the name of the property, it's a variable that contains the name.

But you can still do it, just using bracket notation instead:

    document.write("<p>", prop, ": ", student[prop], "</p>");

Thanks Steven! I finally figured that out through trial and error and wound up with just what you wrote:

for (var i = 0, l = students.length; i < l; i++) {
    var student = students[i];
        for (var prop in student) {
           var value = student[prop];
                document.write("<p>" + prop + " : " +  value  + "</p>");
    }
}