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 trialcody perry
PHP Development Techdegree Student 18,448 PointsWhy does a variable need to be an empty string at the beginning of the for loop?
Why can you not use message without it being set to an empty string before the for loop?
It returns undefined, but shouldn't you be able to set the message variable as just var message; instead of var message = ' '; before using it in the loop?
Does it only do that because you are adding to the variable at the beginning of the for loop? Or should you always set a variable to an empty string when you plan to add content to it?
2 Answers
rydavim
18,814 PointsThis is a great question.
You need to assign message
the empty string value because you are trying to concatenate it in the for
loop. message += something
is the same as message = message + something
. In this case, if you didn't assign a string value to message, you would be trying to concatenate an undefined variable with a string.
This isn't a problem when using the student
variable, because you are assigning it a new value in each new block of the for
loop.
Hopefully that clears things up for you, but please let me know if you have any other questions. Happy coding! :)
cody perry
PHP Development Techdegree Student 18,448 Pointsrydavim Thanks that clears it up a bit! :)