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

Colin Sandlin
Colin Sandlin
4,512 Points

Why do you have to create student = students[i]; instead of just using students[i]?

// Instead of this: //
for(var i = 0; i < students.length; i++) { 
  student = students[i];
  message += '<h2>Student: ' + student.name + '</h2>';
  message += '<p>Track: ' + student.track + '</p>';
}

// Why doesn't this work the same? //
for(var i = 0; i < students.length; i++) { 
  message += '<h2>Student: ' + students.name + '</h2>';
  message += '<p>Track: ' + students.track + '</p>';
}

2 Answers

Sean T. Unwin
Sean T. Unwin
28,690 Points
// Why doesn't this work the same? //
for(var i = 0; i < students.length; i++) { 
  message += '<h2>Student: ' + students.name + '</h2>';
  message += '<p>Track: ' + students.track + '</p>';
}

This doesn't work because students is an Array, which is why we loop through it.

Each item in the Array is a student, so in the first (working) example, we assign the current Array item as student for easier readability, primarily.

Now, you could do the same without assigning the current iteration of students to a variable, although in that case we would need to use bracket notation on the Array of the current Index -- the value of i in the for loop. This bracket notation is visible in the working example when we assign student to the current iteration of students.

In order for your example, which I quoted above, to work we need to add that bracket notation. This would look like the following:

// This will work now //
for(var i = 0; i < students.length; i++) { 
  message += '<h2>Student: ' + students[i].name + '</h2>'; // <-- Note: the bracket notation
  message += '<p>Track: ' + students[i].track + '</p>'; // <-- Note: the bracket notation
}

I hope that helps to clarify.

Colin Sandlin
Colin Sandlin
4,512 Points

Ah, yes that makes sense. I appreciate you showing how a tweak to my code could have worked, which in turn clarifies why the instructor did it the other way in his example.