Java Reference
In-Depth Information
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 fi rst create a simple function that takes just one param-
eter (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
defi ne what parameters the function expects to be passed. There's only one parameter — the user name.
Defi ning parameters is a little like defi ning 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 defi ned your function name and its parameters; all that's left is to create the func-
tion 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 param-
eters as normal variables. The value that the parameter has will be that specifi ed 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 function is executed,
the variable userName, used in the body of the function code, will contain the text “Paul”.
Suppose you wanted to pass two parameters to your function — what would you need to change? Well,
fi rst you'd have to alter the function defi nition. Imagine that the second parameter will hold the user's
age — you could call it userAge since that makes it pretty clear what the parameter's data represents.
Here is the new code:
function writeUserWelcome(userName, userAge)
{
document.write(“Welcome to my website” + userName + “<br />”);
Search WWH ::




Custom Search