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 JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2 Solution

Gremyko Coleman
Gremyko Coleman
9,388 Points

For 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
Mike Hatch
14,940 Points

Because 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.

Gremyko Coleman
Gremyko Coleman
9,388 Points

ooh, thats right, I am thinking the students was an object , I forgot in the video they did say its an array

Mike Hatch
Mike Hatch
14,940 Points

Arrays 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.

James Estrada
seal-mask
.a{fill-rule:evenodd;}techdegree
James Estrada
Full Stack JavaScript Techdegree Student 25,864 Points

You 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).