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 trialGremyko Coleman
9,756 PointsFor this video why was a for loop used , instead of a "for in" loop?
function print(message){
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
var HTML = '';
var students = [
{
Name: 'Jerry',
Track: 'Front End Development',
Achievements: 10,
Points: 1216
},
{
Name: 'Angelica',
Track: 'iOS',
Achievements: 8,
Points: 1000
},
{
Name: 'Robert',
Track: 'Full Stack Developer',
Achievements: 47,
Points: 17000
},
{
Name: 'Jordan',
Track: 'Front End Developer',
Achievements: 7,
Points: 900
},
{
Name: 'Kai',
Track: 'Full Stack Developer',
Achievements: 36,
Points: 14000
}
];
for (var i = 0; i < students.length; i++){
HTML += '<br>'
HTML += '<b>Student: ' + students[i].Name + '</b><br>';
HTML += 'Track: ' + students[i].Track + '<br>';
HTML += 'Achievements: ' + students[i].Achievements + '<br>';
HTML += 'Points: ' + students[i].Points + '<br>';
}
print(HTML);
2 Answers
Mike Hatch
14,940 PointsBecause it's an array. The for
loop is standard practice to iterate over an array. According to Douglas Crockford in his book Javascript: The Good Parts (Pages 60 - 61) it has to do with order and performance. When iterating over the properties of an object it is standard practice to use a for in
loop.
James Estrada
Full Stack JavaScript Techdegree Student 25,866 PointsYou need to use the standard for loop to iterate through each student. Then you can use a for in loop to go through each property of the object literal (student).
Gremyko Coleman
9,756 PointsGremyko Coleman
9,756 Pointsooh, thats right, I am thinking the students was an object , I forgot in the video they did say its an array
Mike Hatch
14,940 PointsMike Hatch
14,940 PointsArrays are objects, too. Most data in Javascript are objects and that includes functions. I highly recommend you read those two pages I linked you to.