Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Akeia Escobar
Akeia Escobar
1,957 Points

I got stuck trying to access the value

When I run this code it prints "undefined" at the top. Then name, track, etc., but the values of the object also print undefined. What am I doing wrong?

var HTML;

let students = [
   name: 'Cayden',
   track: 'C#',
   achievements: 10,
   points: '2123'

   name: 'Akeia',
   track: 'Full Stack Development',
   achievements: 15,
   points: '4253'

   name: 'Yaya',
   track: 'Front End Development',
   achievements: 13,
   points: '2435'

   name: 'Jason',
   track: 'Beginner Python',
   achievements: 12,
   points: '2321'

   name: 'Ashley',
   track: 'iOS',
   achievements: '9',
   points: '1324'

// print function

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

//for loop to access array

for (i = 0; i < 4; i += 1 ) {
  for (studentData in students[i]) {
  HTML += '<p>' +  studentData + ': ' + studentData[students] + '</br>'


2 Answers

1) Initialize HTML with an empty string. Without a value you have the first undefined.

var HTML = "";

2) Access properties for the current array object students[i]

  HTML += '<p>' +  studentData + ': ' + students[i][studentData] + '</br>'

3) Use students.length (which equals 5 not 4) here:

for (i = 0; i < students.length; i += 1 ) {
Akeia Escobar
Akeia Escobar
1,957 Points

Thanks! That worked. Can you explain why students[i][studentData] works?

It's not really clicking

From MDN on bracket notation:

Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it.

It then goes on to give an example of accessing properties of a car object but the syntax is basically:


For the code students[i] is the object and studentData is the property

The first example here is similar

Loop through the properties of an object:

var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
  text += person[x] + " ";
Akeia Escobar
Akeia Escobar
1,957 Points

Thanks. That helps a lot!