Java Reference
In-Depth Information
When JavaScript comes across a return statement in a function, it treats it a bit like a break
statement in a for loop—it exits the function, returning any value specified after the return
keyword.
You'll probably find it useful to build up a “library” of functions that you use frequently in
JavaScript code, which you can reference in your pages.
Having created your functions, how do you use them? Unlike the code you've seen so far, which
executes when JavaScript reaches that line, functions only execute if you ask them to, which is
termed calling or invoking the function. You call a function by writing its name at the point where
you want it to be called and making sure that you pass any parameters it needs, separated by
commas. For example:
myTemp = convertToCentigrade(212);
This line calls the convertToCentigrade() function you saw earlier, passing 212 as the parameter
and storing the return value from the function (that is, 100 ) in the myTemp variable.
Have a go at creating your own functions now, taking a closer look at how parameters are passed.
Parameter passing can be a bit confusing, so you'll first create a simple function that takes just one
parameter (the user's name) and writes it to the page in a friendly welcome string. First, you need to
think of a name for your function. A short but descriptive name is writeUserWelcome() . Now you
need to define what parameters the function expects to be passed. There's only one parameter—the
username. Defining parameters is a little like defining variables—you need to stick to the same
rules for naming, so that means no spaces, special characters, or reserved words. Let's call your
parameter userName . You need to add it inside parentheses to the end of the function name (note
that you don't put a semicolon at the end of the line):
function writeUserWelcome(userName)
Okay, now you have defined your function name and its parameters; all that's left is to create the
function body—that is, the code that will be executed when the function is called. You mark out
this part of the function by wrapping it in curly braces:
function writeUserWelcome(userName){
document.write("Welcome to my website " + userName + "<br />");
document.write("Hope you enjoy it!");
}
The code is simple enough; you write out a message to the web page using document.write() .
You can see that userName is used just as you'd use any normal variable; in fact, it's best to think
of parameters as normal variables. The value that the parameter has will be that specified by the
JavaScript code where the function was called.
Let's see how you would call this function:
writeUserWelcome("Paul");
Simple, really—just write the name of the function you want to call, and then in parentheses
add the data to be passed to each of the parameters, here just one piece. When the code in the
Search WWH ::




Custom Search