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

Catelinn Xiao
Catelinn Xiao
4,139 Points

Why can't I use for in loop for student objects?

Can I use for in loop to access the properties of each student object like this?

for ( var i = 0; i < students.length; i += 1 ) {

student = students[i];

for ( var key in student ) { message += "<p>" + student.key + "</p>"; } }

I tried, it showed "undefined" in the output. Why?

2 Answers

Javier Mera
Javier Mera
16,472 Points

Because key represents each property in the object, you have to use bracket notation to access each student object, in the array. So for example, students[0][key].Name, would give you the Name of the first student in the array.

So in your case, you'd have to use student[key], to access a student in each iteration.

for ( var key in student ) { message += "<p>" + student[key] + "</p>"; } }

Rick Buffington
Rick Buffington
8,146 Points

I'm thinking that you probably can't use student.key - you would have to use just key because student doesn't contain a field or method called key. key is the iterator for your foreach loop.