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

KRIS NIKOLAISEN
KRIS NIKOLAISEN
54,288 Points

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.