Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

486 LESSON 17: Introducing JavaScript


Even though the test in the loop will not pass , it will still run once because the condition
is checked after the first time the body of the loop runs.

When you’re using while loops, avoid creating infinite loops. This
means that you must manipulate one of the values in the looping
condition within the body of your loop. If you do manage to create
an endless loop, about the only option you have is to shut down
the web browser. If you’re going to iterate a specific number of
times using a counter, it’s usually best to just use a for loop.

CAUTION

Functions


Functions are a means of grouping code together so that it can be called whenever you
like. To create a function, you declare it. The following code includes a function declara-
tion :
function writeParagraph(myString) {
document.write("<p>" + myString + "</p>");
}

A function declaration consists of the function keyword, a function name, a list of
parameters the function accepts (in parentheses), and the body of the function (enclosed
in curly braces). This function is named writeParagraph , and it accepts a single param-
eter, myString. Function parameters are variables that are accessible within the body of
the function. As you can see, this function prints out the value passed in as an argument
inside a <p> tag. After I’ve declared this function, I can then use the following code later
in the page:
writeParagraph("This is my paragraph.");
It will produce the output:
<p>This is my paragraph.</p>

When it comes to the values passed to functions, you’ll see them
referred to as parameters or as arguments. Technically, the vari-
ables listed in the function declaration are parameters, and the
values passed to the function when it is called are arguments.

NOTE
Free download pdf