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

"undefined" shows up before the student list. What have I missed?

var students = [
  {name: "Asia", track: "Front End Development", achievements: 3100, points: 4000},
  {name: "Bien", track: "iOS", achievements: 100, points: 200},
  {name: "Bea", track: "PHP", achievements: 2100, points: 3000},
  {name: "Bella", track: "Business Development", achievements: 1100, points: 3000},
  {name: "Basil", track: "Web Design", achievements: 200, points: 200},
  {name: "Faye", track: "Ruby", achievements: 4100, points: 5000}
];

var studentName,
    track,
    achievements,
    points,
    studentList;


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


for (var i=0; i<students.length; i++) {
    studentName = students[i].name;
    track = students[i].track;
    achievements = students[i].achievements;
    points = students[i].points;
    studentList += "<p>Name: " + studentName + "; " + " Track: " + track + "; "+ " Achievements: " + achievements + "; " + " Points: " + points + "</br></p>";
    print(studentList);
}

I don't know why undefined is shown on the output.

undefined

2 Answers

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

to get rid of the undefined you only need to set studentList to the empty string, since that is all you are printing in the loop. unless you initialize it to the empty string, it is nothing, it is literally undefined, so when you start tacking strings to it and print you are adding strings to undefined, so it prints undefined then the strings you added to the end. by initializing to the empty string you give it a type and thus nothing is undefined about it, you can concatenate more strings to it and everything prints as expected.

Hi james south, that worked. :) Should I do it to all the keys or just "name"? Also, what is the purpose for this? Thanks!