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

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
216,012 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>";
 }