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

Joseph Escobedo
seal-mask
.a{fill-rule:evenodd;}techdegree
Joseph Escobedo
Full Stack JavaScript Techdegree Student 4,172 Points

Why do I keep getting undefined in my loop? I cant figure out how to get rid or why its showing up.

When i run the code, i get an undefined thats posted on the webpage before the actual data i want displayed and I cant figure out why this is happening.

var students = [
  {
    name: 'Joe',
    track: 'Full Stack JavaScript',
    achivements: 10,
    points: 1000
  },
  {
    name: 'Sally',
    track: 'IOS',
    achivements: 25,
    points: 1500
  },
  {
    name: 'Zack',
    track: 'Ruby',
    achivements: 5,
    points: 500
  },
  {
    name: 'Mark',
    track: 'C++',
    achivements: 20,
    points: 800
  },
  {
    name: 'Sammy',
    track: 'Java',
    achivements: 15,
    points: 700
  }
];

var html;
var student;

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

for(let i = 0; i < students.length; i++) {
  student = students[i];
  html += `<h2>Student: ${student.name}</h2>`;
}

1 Answer

Steven Parker
Steven Parker
231,248 Points

The "html" variable isn't initialzed, so the first time a string is added on to it (with "+="), it's value starts out as "undefined".

Just set it to an empty string when you declare it:

var html = "";
Joseph Escobedo
seal-mask
.a{fill-rule:evenodd;}techdegree
Joseph Escobedo
Full Stack JavaScript Techdegree Student 4,172 Points

I just figured it out a couple minutes ago. Ive always wondered why that happens, glad after all this time, I understand. thanks for your quick response!

Steven Parker
Steven Parker
231,248 Points

And congratulations on resolving it yourself before you saw my answer! :+1:
Happy coding!