HTML and CSS Reference
In-Depth Information
7.1.1 Function Declaration and Invocation
Functions must be declared before they can be used. Normally functions are placed in
the <head> tag of the HTML document to ensure that they are defined before used.
Within the <script> tag itself, they can go anywhere. Function definitions are often
stored in external JavaScript files or libraries (see “JavaScript from External Files” on
page 22 of Chapter 1).
To define a function, the function keyword is followed by the name of the function
and a set of parentheses. The parentheses are used to hold parameters, values that are
received by the function. The function's statements are enclosed in curly braces.
function bye() { document.write ("Bye, adios, adieu, au revoir..."); }
Once you define a function, you can use it. JavaScript functions are invoked by call-
ing the function; for example, bye() . A function can be called directly from within the
<script> tag, from a link, or when an event is triggered, such as when the user presses a
key. When called, the function's name is followed by a set of parentheses that may con-
tain messages that will go to the function. These messages are called arguments.
To check whether the function has been defined or if it is truly a function, use the
typeof operator; for example, typeof(function_name).
Function definition:
function function_name () {statement; statement;}
function function_name (parameter, parameter){statement; statement;}
Function call:
function_name(argument1, argument2, ...)
<head><title>A Simple Function</title>
<script type="text/javascript">
function welcome(){ // Function defined within <head> tags
var place="San Francisco";
alert("Welcome to "+ place + "!");
Search WWH ::

Custom Search