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


Team Account
Team Account
1,958 Points

Why not use a for...in loop within the array, rather than writing a line for each value?

I thought that in order to use the skills we've learned in the course so far, we would be required to use the for... in loop to loop through the students object, as well as looping through the array.

I use the following code, and was wondering if there's any reason not to do it this way? This way, if additional key/values are added to the data, it would all be pulled through automatically.

var message = '' ;

for ( var i = 0; i < students.length; i++ ) {
  var student = students[i];
  message += '<div class="student">';
  for ( var key in student ) {
    message += '<p class="' + key + '">' + key + ': ' + student[key] + '</p>';
message += '</div>';

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


1 Answer

Steven Parker
Steven Parker
228,095 Points

First off, keep in mind that the course examples are primarily to illustrate and reinforce the concepts being introduced. They may not be the only way, or most concise or efficient way, to perform a particular task.

But, that said, one advantage that comes to mind for the code shown in the video and course downloads is that it guarantees the display order of the items, where the loop would not. Another advantage is that it will still display a category (along with "undefined" for the value) if the category is missing from the student record.

Of course, if you wanted, you could expand your code to combine the advantages of both approaches.