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 Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

Enemuo Felix
Enemuo Felix
1,895 Points

I'm confused. How did he do it?

How did Dave use 'message' to print the whole of the code. The first place he introduced it was in the print function as an arguement. How come he could be able to run the whole code with it? Can somebody patiently explain this for me? Steven Parker andren . Anyone?

1 Answer

Steven Parker
Steven Parker
229,708 Points

:bell: Hi, I got your alert.

You're right that "message" is just the name of the parameter of the "print" function. So the real work is done by the call to "print(html)".

The "html" variable is built up in the loop that runs 100 times, and each time it makes the "html" string bigger by adding a new div element to it (with a random color). Note that the new string is added to "html" using a concatenating assignment operator ("+="). Instead of replacing the contents as a normal assignment would, this operator adds the new string onto the end of what is already there.

So on the line with "print(html)", the "html" variable is holding 100 div elements.

Does that clear it up?

Enemuo Felix
Enemuo Felix
1,895 Points

Thank you Steve, i already know how the html is used to by Dave. What I can't really grasp is How he used the print function to print out the whole program in place of document.write ? Is that function really Necessary in the code? And why does he have to include 'message' in the parenthesis and why not leave it empty?

Steven Parker
Steven Parker
229,708 Points

As defined in the video, the "print" function just calls "document.write", so it is essentially the same thing. But you're getting ahead of the course, because at the end of the video, Dave says, "... there's actually a really good reason for moving the document.write call into its own function. But you'll have to wait until the next section of this course to find out why." So hold on to that question while you continue through the next course stage.

And "message" is in parentheses because it is the parameter of the "print" function, and also the argument to the "document.write" call. JavaScript syntax requires parentheses for both parameters and arguments.