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

Alan Sea
Alan Sea
6,781 Points

Only thing printing to the browser window is 'undefined'...?

https://w.trhou.se/s8stx77bkk

The console logs no error. Any help pointing to my mistake is appreciated. Thanks!

(Also, can you please explain why a "for" --and not a "for in"--loop is more appropriate for this exercise? Before watching the solution, I had tried returning the properties with a "for in" loop, but it wouldn't print the expected result in the right format. It returned the array position and its corresponding name next each other...repeated twice on seperate lines

Like so:

0 John Smith 1 Traci Jones etc......

0 John Smith 1 Traci Jones etc.... )

1 Answer

Toni Ojala
Toni Ojala
17,570 Points

In the for loop you need to be checking i against the length of the students array. Right now it's being checked against the students array itself, which means the for loop is not running even once. Here's how to do it:

for(var i = 0; i < students.length; i++) {
...
}

The reason you're getting the undefined printed at the top of the page is because the message variable is not instantiated as an empty string. This makes the message variable hold some arbitrary information in it and being printed as undefined. So to fix it you just need to instantiate it as an empty string at the beginning like this:

var message = "";

I believe for in loops are meant to be used with objects and the students array is an array of objects. If you use a for in loop with an array, the variable defined in the for loop will hold the index of the array. So to use for in with the students array here, you would need to do it like this:

for (var student in students) {
  message += '<h2>Student:' + students[student].name +'</h2>';
  message += '<p>Track: ' + students[student].track +'</p>'
  message += '<p>Achievements : ' + students[student].achievements +'</p>'
  message += '<p>Points : ' + students[student].points +'</p>'
}

The variable student merely holds the current index value through each iteration of the loop which is exactly what i is doing in a regular for loop.

Alan Sea
Alan Sea
6,781 Points

Thanks so much.