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

adam åslund
PLUS
adam åslund
Courses Plus Student 12,184 Points

Why dose creating var message = ''; remove undefined?

When I started first completed the challenge my code was like this

var message;

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


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



print(message);

Then I would get a undefined as the first html text printed. I then looked back on the older code and saw the code from "array quiz challange" where we build this function

function buildList(arr) {
  var listHTML = '<ol>'
  for (var i = 0; i < arr.length; i++) {
    listHTML += '<li>' + arr[i] + '</li>';
  };
  listHTML += '</ol>'
  return listHTML;
}

Then I added a <div> to wrap my massage. That removed the undefined, but instead I now had a extra html element. Saw that in the solution video Dave just added

var message = '';

My question is why dose it return undefined first if there isn't a string in message before the for loop?

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi adam åslund,

The reasoning behind this is very simple, whenever you create a new variable in JavaScript and don't assign it a data value it automatically references undefined as it's value because that is what the ECMAScript specification says to do with in this type of situation, however when we assign a String data value it now references an object that contains valid information for code further down to work with.

So in the case of your above code message += would fail if an empty string wasn't assigned first, whereas if we assign that empty string the compound operator += will simply append one string to another.

Hope that helps.