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

Prabhakar R
Prabhakar R
3,603 Points

Why My code is not working

var sd = [
  {name: 'Mahi', track: 'FullStack', achievements: 2, points: 100},
  {name: 'repal', track: 'FullStack', achievements: 3, points: 90},
  {name: 'Cherry', track: 'FullStack', achievements: 4, points: 80},
  {name: 'Pan', track: 'FullStack', achievements: 5, points: 70},
  {name: 'Prabha', track: 'FullStack', achievements: 6, points: 60}
];
let student;
let message = '';

function print(message){
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML='message';
}

for (let i = 0; i <= sd.length; i += 1){
  student = sd[i];
  message += '<h2> name: ' + student.name + '</h2>';
  message += '<p> Track: ' + student.track + '</p>';
  message += '<p> Achi: ' + student.achievements + '</p>';
  message += '<p> Points: ' + student.points + '</p>';

}

print(message);


====================

VM75:19 Uncaught TypeError: Cannot read property 'name' of undefined
    at <anonymous>:19:38
(anonymous) @ VM75:19

1 Answer

1) The condition for your loop to run i <= sd.length; includes sd.length. This then includes an index of 5 when the highest index for sd is 4 (index starts at 0). You see undefined in the console because sd[5] is undefined. The condition should just be i < sd.length;.

2) You also have message in quotes here.

outputDiv.innerHTML='message'

This will set the inner HTML to 'message' instead of the value of the variable message. Remove the quotes.