JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

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
174,098 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?

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
174,098 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.