
Functions are a way to avoid having to type the same part of a script over and over again. If you have a section of script that you want to repeat, such as asking for the name in an address book, the part of the script that asks for the name can be put
into a function that we will call Getname. The Getname function can then be run whenever you need to get a name. Back when you were learning about the Script tag, you learned that you can have more than one section of script. Normally when you define
functions (defining means to create) you put that part of the script in the head of your web page. The part of script that calls the function (calling is when the script runs the function from a different part of the script) is then located in the body o
f the page.
To define a function you would use the function command. This example shows you how to define the Getname function.
<HTML>
<Head>
<Script Language=JavaScript>
//Java Script appears Here
//Download Netscape Navigator 2.0 to use it.
<!--hiding from other Browsers
function getname(){
var name=prompt ("What is Your Name?","Name")
return name
}
// Stop hiding from other Browsers -->
</Script>
</Head>
<Body>
</Body>
</HTML>
We use the prompt method to ask the user to enter a name. In defining a function the function command goes first, followed by the name you want to call the function. The parenthses are if you want to pass a variable to the function. For ins
tance you have employee 5 that you want to get names for. You could tell the script which employee's name to ask for using this variable. In our case we only want to know the user's name. The script that goes with the function is enclosed in brackets,
any script that you want in the function must be between these two brackets. The last command in the function is the return. The return command tells the function what value it should send back to the main script when it is done
. In this example the function returns the value of the name that the user types in.
To put it all together the final script would be as follows:
<HTML>
<Head>
<Script Language=JavaScript>
//Java Script appears Here
//Download Netscape Navigator 2.0 to use it.
<!--hiding from other Browsers
function getname(){
var name=prompt ("What is Your Name?","Name")
return name
}
// Stop hiding from other Browsers -->
</Script>
</Head>
<Body>
<Script Language=JavaScript>
//Java Script appears Here
//Download Netscape Navigator 2.0 to use it.
<!--hiding from other Browsers
alert("Hello "+getname())
// Stop hiding from other Browsers -->
</Script>
</Body>
</HTML>