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

H Yang
H Yang
2,066 Points

Undefined, and using student.name vs students[i].name

The code.

var message = "";
var student;

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

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

print(message);

A couple of questions here. When I didn't have

var message = "";

and had

var message;

instead, I got a line at the top of my page that said undefined. The rest of the code otherwise worked. What's going on here? Why did I have to declare message that way?

Second question- the instructor declared a variable "student" as being defined as equal to "students[i]". Instead of doing that and using "student", I just used "students[i] in my code. My code worked; however, is it a better practice to do as the instructor did?

Thank you!

1 Answer

andren
andren
28,558 Points

When you use the += operator you add a value to the value that is already in the variable. If you assign nothing to the message variable then by default it will contain the value undefined. When undefined is concatenated with a string it will be converted to a string itself. That's why you get undefined at the start. When you actually define message as an empty string then it starts out as a string and just has content added to it, which is the intended behavior.

There is no difference behavior wise between assigning a variable called students to student[i] versus just using student[i] directly. The only difference is in how much you have to type. It's pretty common to do what the instructor did since it reduces the amount of writing, and arguably looks a bit cleaner. But it's certainly not mandatory.

H Yang
H Yang
2,066 Points

Thanks andren, that makes a lot of sense.