JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2 Solution

Mavis Lok
Mavis Lok
2,774 Points

Doubtful of my code although it works

After watching the teacher's methods and reading everyone else's codes/questions, I'm starting to doubt my code despite it working.

for ( var prop in students ) {

  document.write('<h2>Student: ' + students[prop].name + ' </h2>');
   document.write('<p>Name: ' + students[prop].track + ' </p>');
    document.write('<p>Achievements: ' + students[prop].achievements + ' </p>');
     document.write('<p>Points: ' + students[prop].points + ' </p>');

}

How can I make it better?

2 Answers

Gabriel Pierce-Lackey
MOD
Gabriel Pierce-Lackey
Treehouse Moderator 10,972 Points

What are you doubting about it?

The only thing I would recommend is using/making the print function as I don't think you will really use document.write that much in a practical way. Everything else is the same concept, but using a for in loop instead of the normal kind of loop. There are differences between the two and how they loop but for this purpose they work the same.

Steven Parker
Steven Parker
171,242 Points

What kind of doubts are you having about it?

I don't see any technical issues, but since the loop variable will represent the index of one of the elements of the "students" array, the name "prop" is a peculiar choice for it. A typical convention for a numeric loop index is to name it "i", but that will make no difference to performance.

Another minor readability issue is that it's usually considered a "best practice" to indent all lines that are at the same nesting level by the same amount.