Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

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;
};

print(message);

1 Answer

Steven Parker
Steven Parker
215,954 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.