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 trialJulia T
2,755 PointsIs line 1's var message = ""; necessary? Or will var message; also work?
i.e Is it obligatory to assign a value (empty string in this case) to the variable message in the beginning?
var message = ''; //line 1 here
var student;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
// some more code...
https://teamtreehouse.com/library/javascript-loops-arrays-and-objects/tracking-data-using-objects/the-build-an-object-challenge-part-2-solution (code around the ~2:46 minute mark)
1 Answer
Steven Parker
231,268 PointsFor the code shown here, the variable "message" is not needed at all and the first line can be removed.
The "message" in the function is a parameter and will be used in preference to a global by the same name, even if one exists.
But later in the video, more code is added which does use the variable, and that code concatenates strings onto it. For that reason, it's important that it be assigned with an empty string to start with. Otherwise, the word "undefined" will appear at the beginning of the concatenated string.
Julia T
2,755 PointsJulia T
2,755 Pointsoh after testing a bit I think the "" is there to prevent undefined when you return the message string.