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

Tou Lee
Tou Lee
6,608 Points

Works but prints "undefined" too...

Technically, it works. Somehow it's printing 'undefined' as the first value. Not sure where it's coming from. Thoughts?

var student;
var name;
var track;
var achievements;
var points;
var html;

var students = [ 
  { 
    name: 'Bjorn Uchekov',
    track: 'Front End Development',
    achievements: 158,
    points: 14730
  },
  {
    name: 'Sammy Yamatori',
    track: 'iOS Development with Swift',
    achievements: 175,
    points: 16375
  },
  {
    name: 'Darth Fador',
    track: 'PHP Development',
    achievements: 55,
    points: 2025
  },
  {
    name: 'Don Chavez',
    track: 'Learn WordPress',
    achievements: '40',
    points: 1950
  },
  {
    name: 'Lil\' Kim Jung Uno',
    track: 'Rails Development',
    achievements: 5,
    points: 350
  }
];

var print = function(msg) {
  var box = document.getElementById('output');
  box.innerHTML = msg;
};

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

print(html);

2 Answers

Akhter Rasool
Akhter Rasool
8,597 Points

You havent initialized our html variable. You cant append '+=' a variable without having anything in it. You must initialize it to something or initialized it to "". initialization is obligatory.

Tou Lee
Tou Lee
6,608 Points

I see! That makes sense.

Ryan Zimmerman
Ryan Zimmerman
3,854 Points

So the HTML variable you are starting with is undefined and it is adding to the html. Start by declaring it with a '<div>' and close it before pushing to innerhtml with a '</div>'.

Ryan Zimmerman
Ryan Zimmerman
3,854 Points

i didn't use your print function I just logged it to the console

or you could start the html with var html = ''

Tou Lee
Tou Lee
6,608 Points

Ahh, you're right.