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

Uncaught TypeError: Cannot read property 'name' of undefined.

In this code challenge 'The Build an Object Challenge, Part 2' , I have gone through the solution and did exactly the same as Dave did. But the error 'Uncaught TypeError: Cannot read property 'name' of undefined' has appeared eventhough the code is exactly the same.

var message = '';
var student;

function print(message) {
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}
  for( var i=0; i<= students.length; i+=1) {
    student = students[i];
    message += '<h2>Student: ' + student.name + '</h2>';
  }
  print(message);

Hi Ajas, your variable student is not defined. It should have an object with a name like:

var student = {
    name: 'Ajas';
}

I am working with this code and it's all clear here. I've used a new variable student = students[i]; to access the name with student variable. I cannot understand the issue here.

var students = [ 
  { 
    name: 'Dave',
    track: 'Front End Development',
    achievements: 158,
    points: 14730
  },
  {
    name: 'Jody',
    track: 'iOS Development with Swift',
    achievements: '175',
    points: '16375'
  },
  {
    name: 'Jordan',
    track: 'PHP Development',
    achievements: '55',
    points: '2025'
  },
  {
    name: 'John',
    track: 'Learn WordPress',
    achievements: '40',
    points: '1950'
  },
  {
    name: 'Trish',
    track: 'Rails Development',
    achievements: '5',
    points: '350'
  }
];

2 Answers

Ajas, pay attention to what you wrote in the for loop condition:

i <= students.length;

students.length will give you 5 Meanwhile var i will starts to increment from 0, 1, 2, 3, 4, 6, this way you will get 6 loops and the 6th is undefined, because there are no 6 items in the student array. Your for loop condition should look like this i < students.length;

Take a look at this code:

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

for(var i = 0; i < students.length; i += 1) {
    student = students[i];
    message += '<h2>Student: ' + student.name + '</h2>';
  }
  print(message);

Thanks a lot.