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

Yi Zhang
Yi Zhang
3,721 Points

Why do we need var message = ''; at the beginning of the code?

Why does var message = ' '; mean?Why do we need to add it to the message variable in the loop?

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! JavaScript is pretty smart. In many languages you have to explicitly say what kind of data a variable is going to hold before you can even use it. JavaScript has something it calls "type inference" where it makes a best guess as to what the data type is by how you use it. My advice is to run this in the console and take a look at what it tells you:

var message1;
var message2 = '';
message1 += 2;
message2 += 2;
console.log(message1);
console.log(message2);

In this example, we declare a variable named message1. Because we don't iniitialize with a number or a string or anything else, JS says that it is of type "undefined". And it's right. We haven't yet put anything in that variable so it has no idea what it's supposed to contain. In the message2 variable we start by initializing it as an empty string. So JavaScript knows that even though there currently are no characters in that string, it will later hold a string. So when we do the concatenation with the 2, it understands we want a string and magically converts it for us!

It's always a good idea to initialize something you know will contain a string later with an empty string to start with. As you can see there can be unexpected consequences with concatenation later on down the road if this is not done.

Hope this helps! :sparkles:

Max Botez
Max Botez
5,146 Points

Hi and thank you for pretty explanatory answer, this is great!

So basically both variables are empty but the difference for the second variable it good to dignify as a empty string as long as first variable does not know what type of data it is going to contain. And for second variable if you know that its going to be a string then we are kind of helping and trying to eliminate errors in future.

Thanks a lot, Max