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 trialMelinda Golden
Full Stack JavaScript Techdegree Graduate 25,815 PointsI used a "for in" loop and my code works. Is the "for" loop better practice because it is an array of objects?
Here is my code: https://jsfiddle.net/mmgolden/jmtzqs8u/
2 Answers
Dan Oswalt
23,438 PointsFor...in works for arrays, but it is not recommended. It's like using a deprecated method, sure it may work, but it's not really the right tool for the job, and you may get unexpected results. This is not the case for iterating over objects though, it's useful for that.
John Stamps
1,712 PointsThank you, Dan. I did the same thing that Melinda did, because it was the last loop I remembered from the videos.
for (var property in students) { console.log(students[property]); html = document.getElementById("output").innerHTML; document.write(html += "<h2>Student: " + students[property].name + "</h2>"); document.write(html = "<p>Track: " + students[property].track + "</p>"); document.write(html = "<p>Achievements: " + students[property].achievements + "</p>"); document.write(html = "<p>Points: " + students[property].points + "</p><br>"); };
Dave created a separate student variable. Why create the separate variable? And why not use the for... in loop if we're indeed looping through objects?
Thanks in advance. I feel like I'm actually learning something!
Dan Oswalt
23,438 PointsDan Oswalt
23,438 PointsAnd to add to the second part of your question, the contents of the array or object don't affect how you iterate over them.
Melinda Golden
Full Stack JavaScript Techdegree Graduate 25,815 PointsMelinda Golden
Full Stack JavaScript Techdegree Graduate 25,815 PointsThanks Dan, that makes sense.