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

Can u check this code for me ?

var students = [
    {name : 'Jay', track : 'Techdegree Javascript', achievments: '3', points: '2390' },
    {name : 'Leo', track : 'Techdegree Javascript', achievments: '3', points: '2390' },
    {name : 'Mavi', track : 'Techdegree Javascript', achievments: '3', points: '2390' },
    {name : 'Mamma', track : 'Techdegree Javascript', achievments: '3', points: '2390' },
];
function print (message) {document.write (message)}  
var i = 0;
for ( var i=0; i< students.length ; i+= 1)  {
for (var prop in students[i]) {
print (prop);  
print ('<li>'+ students[i][prop]+ '</li>');
}  
}

3 Answers

Steven Parker
Steven Parker
231,269 Points

Since you're creating list items in the loop, you probably want to enclose them in a list so you might add list tags before and after the loop. You can also put the property name inside the list item with each value. And you don't need the separate "var i = 0;" line since that is done as part of the outer loop:

for (var i in students) {
    print("<ul>");
    for (var prop in students[i]) {
        print("<li>" + prop + ": " + students[i][prop] + "</li>");
    }
    print("</ul>");
}
Sharath Chandra
Sharath Chandra
3,957 Points

Steven Parker , I remember Dave mentioning that the for in loop is specific to looping through objects. In your code I see that you've used the for in loop to loop through the students array. Can we use for in loops to loop through arrays too? Could you please elaborate. I'm having some trouble understanding the concept of loops.

Steven Parker
Steven Parker
231,269 Points

In JavaScript, arrays actually are objects. One thing to be aware of when using the "for...in" loop with an array is that it treats the index values as keys, and returns them as strings instead of numbers. I get away with that here because the system performs type coercion when I subscript the array with them.

for (var i = 0; i < students.length; i += 1) {
  console.log(typeof i);  // "number"
}
for (var i in students) {
  console.log(typeof i);  // "string"
}

Great ! Thanks for the tips Steven.