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 
   
    SeHyun Choi
3,441 PointsWhat is difference between var message; and var message ="";
What is the difference between
var message;
and
var message ="";
Aren't they the same? Aren't they all empty variable called message?
When I do var message; Then my code doesn't loop but when i do var message =""; Then it correctly loops. What is the difference?
CODE
var students = [
    {
        name : "Sarah",
        age : 26,
        country : "USA"
    },
    {
        name : "Sammy",
        age : 23,
        country : "USA"
    },
    {
        name : "Yohan",
        age : 46,
        country : "USA"
    },
];
var student;
var message ="";
function print(message) {
    var printIt = document.write(message);
    return printIt;
}   
for(var i = 0; i < students.length; i += 1) {
    student = students[i];
    message += "<h2>Student: " + student.name + "</h2>";
    message += "<p>Age: " + student.age + "</p>";
    message += "<p>Country: " + student.country + "</p>";
}
print(message);
1 Answer
 
    Steven Parker
243,160 PointsWhen you write just "var message;" you declare the variable as existing, but it has no contents yet.   When you add the ="" to it, you are putting a string into it.  The string happens to be empty itself, but it's still a string and the variable contents are no longer undefined.
The "+=" operator is a special kind of assignment that adds onto the contents a variable already has.  So it works fine with a variable that starts with an empty string in it, but not with one that is still undefined.
SeHyun Choi
3,441 PointsSeHyun Choi
3,441 PointsThank you.