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

Can I use loop "for in" inside "for" loop in my solution ?

for ( i = 1; i < Students.length; i += 1 ) {
    document.write("<h2>Student:  " + Students[i].Name + "</h2>") ;
    for ( var prop in Students[i]) {
        document.write([prop] + ": " + Students[i][prop] + "<br>" );
    }
}

2 Answers

Steven Parker
Steven Parker
231,275 Points

You certainly can nest loops of the same or different types.

But you'll probably want to start the outer loop with "i = 0", since 0 is the index of the first item of an array. And you won't need any brackets around the word "prop" where it is used by itself.

Daniel Grigo
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Daniel Grigo
Full Stack JavaScript Techdegree Graduate 18,815 Points

In addition, if you write down the students name in the outer loop (which I also thought of first), it will be printed again during your inner loop under the "name" property. You could get around that with an if-clause:

 for (var i=0; i<students.length; i++){
   for (var prop in students[i]){
     if (prop=="name"){
      message+="<h2>Student: " +students[i][prop]+"</h2>";
    }
    else {message+="<br>"+prop+ ": "+ students[i][prop];
    }
  }
   message+="<p></p>";
 }