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

Steven Good
Steven Good
2,303 Points

Why student.name and not students.name in the loop?

Regarding the for loop, I kept on getting the result 'undefined' when I viewed the code in the browser. it turns out I typed students.name (with an 's' at the end) instead of student.name. I understand why we are using the dot notation to access the name property of the object. I'm just confused why it is student.name instead of students.name (given that the array variable is students). I've probably missed something very simple, but I'd be grateful if anyone can clarify. Thanks.

for (var i = 0; i < students.length; i += 1) { NOTE 3 student = students[i]; NOTE 4 message += "<h2>Student: " + student.name + "</h2>"; NOTE 5 message += "<p>Track: " + student.track + "</p>"; message += "<p>Achievements: " + student.achievements + "</p>"; message += "<p>Points: " + student.points + "</p>"; }

1 Answer

Erik Nuber
Erik Nuber
20,629 Points

Assuming you followed along with the video for the lesson in your code. He assigns student to the value at each array.

var student = students[i]

because of that, student now holds the object that is equivalent to students[i] and therefore, all values can be accessed using dot notation on student. This basically cut down on some of the coding. you could do

students[i].name

and achieve the same thing. But, it is cleaner to read to assign it to a variable and access it that way. The above achieves the same thing as

var student = students[i];
var nameOfStudent = student.name
Steven Good
Steven Good
2,303 Points

Great explanation. Thanks for explaining the concept to me. Much appreciated.