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
Why is the variable message initialized with a blank string, while the variable search is not?
var message = '';
When I completed the last challenge, I had message initialized as:
This caused the first entry on my HTML document to be undefined. I'm not sure I understand when to or not to initialize a variable with a blank string.
Jennifer NordellTreehouse Teacher
This is all fine and dandy until we get to addition/concatenation. Without
message holding an initial value, if you were to use
message += "something"; it will not know how to handle that. It cannot concatenate or add to an
undefined value. But when assigning an initial value, it can figure that out.
Run this in your browser console and take a look:
var thing1 = 1;
var thing2 = "1";
console.log(thing1 + 2);
console.log(thing2 + 2);
console.log(thing3 + 2);
console.log(thing3 += thing2);
The first line prints 3, which should be self explanatory. The second line however, prints 12. Because it's converting the 2 into a string to match the "1". The third line line prints NaN because this is what happens when you try to add something to an
undefined. And the last one prints undefined1, because you're concatenating a 1 onto the end of
Hope this helps!