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!

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

Reuben Varzea
Reuben Varzea
23,182 Points

Why use student = students[i]?

For the record, if the answer is "It's best practice", I'm okay with that. But, I'd just like to get feedback as the the thought process that says this is the best way to do it.

The code I used:

for (var param in students) {
  message += '<h2>Student: ' + students[param].name + '</h2>"'
  message += '<p>Track: ' + students[param].track + '</p>';
  message += '<p>Points: ' + students[param].points + '</p>';
  message += '<p>Achievements: ' + students[param].achievments + '</p><br/><br/>';

I'm assuming that using a student variable here helps improve readability when creating the message string, but other than that, does it matter? I'm just bothered that other folks seemed to all think to do this, and I didn't. :)

2 Answers

Joshua Edwards
Joshua Edwards
52,175 Points

It is mostly best practice but also because it allows you to use the dot notation which reduces the amount of typing you have to do. It also follows more closely the DRY (don't repeat yourself) principle of coding. Instead of having to constantly type student.params[etc].property, you let the for loop handle selecting out a whole object and you can just type student.property. Not a big typing time saver in this example, but when you start working with objects that have a ton of things that are apart of them it is better to pass in the whole object to work with it.