JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2

slurpee
slurpee
6,694 Points

Why doesn't this work?

https://w.trhou.se/m7gdqqpudu

says something about: Uncaught TypeError: Cannot read property 'name' of undefined at students.js:13

slurpee
slurpee
6,694 Points

nvm I did it write, I just added document.write(message); and it all came up. idk why it said that in console though any ideas on that?

slurpee
slurpee
6,694 Points

nvm it works but not sure how to add the titles of the property beside the value of it. it just shows the value, so like for track it just stats the track value not track:

how do I add this? https://w.trhou.se/8za3xwma2y

1 Answer

Jennifer Nordell
STAFF
Jennifer Nordell
Treehouse Staff

Hi there, Angelo! Yes, you were missing your document.write() to print out the list of students, but there are two more problems here. The reason you were getting that name is not defined is that on your last iteration of the loop, you were trying to access an index outside of the array.

You wrote:

(var i = 0; i <= students.length; i+=1 )

But you meant to write:

(var i = 0; i < students.length; i+=1 )

Note the < instead of <= before students.length. If 5 students are in the array it will have a length of 5. But you are accessing the array starting at an index of 0. This means that the 5th student will be at an index of 4. On the very last iteration, you were trying to access the index of 5, which doesn't exist.

Secondly, your code will only ever print out the last student (if you added the document.write()). In the line where you add the <h2> element, you are not concatenating onto the message string, but overwriting it completely. Here, you simply missed a + sign.

You wrote:

message = "<h2>" + students[i].name + "</h2>";

But that should be:

message += "<h2>" + students[i].name + "</h2>";

Hope this helps! :sparkles:

slurpee
slurpee
6,694 Points

ty, but how do I add this "but not sure how to add the titles of the property beside the value of it. it just shows the value, so like for track it just stats the track value not track:

how do I add this? https://w.trhou.se/8za3xwma2y "

Jennifer Nordell
Jennifer Nordell
Treehouse Staff

Angelo Doe Personally, I think I would just put the name of the property in the HTML like so:

for (var i = 0; i < students.length; i+=1 ) {
  message += "<h2>Name: " + students[i].name + "</h2>";
  message += "<p>Track: " + students[i].track + "</p>";
  message += "<p>Achievements: " + students[i].achievements + "</p>";
  message += "<p>Points: " + students[i].points + "</p>";


};