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

Matthew Laing
Matthew Laing
6,119 Points

I used a for in loop, is this bad practice?

This is the code I used, I was looking for feedback on if the way I done it was bad practice.

var students = [ { name: 'Shelly', track: 'Web Design', achievements: 12, points: 1078 },

{ name: 'David', track: 'iOS', achievements: 17, points: 2087 },

{ name: 'Greg', track: 'Front-end Development', achievements: 23, points: 3023 },

{ name: 'Sharon', track: 'PHP Development', achievements: 32, points: 4022
},

{ name: 'Matthew', track: 'Front-end Development', achievements: 37, points: 3215
}

];

var html = '';

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

for (var prop in students) { html += '<h2>Student: ' + students[prop].name + ' </h2>'; html += '<p>Track: ' + students[prop].track + ' </p>'; html += '<p>Points: ' + students[prop].points + ' </p>'; html += '<p>Achievement: ' + students[prop].achievements + ' </p>'; }

print(html);

1 Answer

Steven Parker
Steven Parker
231,275 Points

A plain "for" loop is recommended for working with arrays for three main reasons:

  • a "for...in" will omit unused indices in a "sparse" array
  • the conventional "for" loop is more efficient
  • the order of elements is not guaranteed to be in sequence in a "for...in" loop

But if I wanted to get fancy, I might use a "for...of" and skip the index:

for (var student of students) {
  html += `<h2>Student: ${student.name}</h2>
           <p>Track: ${student.track}</p>
           <p>Points: ${student.points}</p>
           <p>Achievement: ${student.achievements}</p>`;
}