JavaScript Tutorial for Programmers - Functions
A function groups together a set of statements under a
named subroutine. This allows you to conveniently "call"
the function whenever its action is required. Functions
are a fundamental building block of most JavaScript programs,
so you'll become quite familiar with their use. Before
you can call on a function, of course, you must first
create it. We can break down the use of functions, then,
into two logical categories: defining functions and calling
functions.
defining functions
The function definition is a statement which describes
the function: its name, any values (known as "arguments")
which it accepts incoming, and the statements of which
the function is comprised.
function funcName(argument1,argument2,etc)
{ statements; }
A function doesn't necessarily require arguments,
in which case you need only write out the parenthesis;
e.g. funcName(). If you do specify arguments, those
arguments will be variables within the function body
(the statements which make up the function). The initial
values of those variables will be any values passed
on by the function call.
Generally it's best to define the functions for a
page in the HEAD portion of a document. Since the HEAD
is loaded first, this guarantees that functions are
loaded before the user has a chance to do anything that
might call a function. Alternately, some programmers
place all of their functions into a separate file, and
include them in a page using the SRC attribute of the
SCRIPT tag. Either way, the key is to load the function
definitions before any code is executed.
Consider, for example, a simple function which outputs
an argument to the Web page, as a bold and blinking
message:
function boldblink(message)
{ document.write("<blink><strong>"+message+"</strong></blink>"); }
Some functions may return a value to the calling expression.
The following function accepts two arguments, x and
y, and returns the result of x raised to the y power:
function raiseP(x,y)
{ total=1;
for (j=0; j<y; j++)
{ total*=x; }
return total; //result of x raised to y power
}
calling functions
A function waits in the wings until it is called onto
the stage. You call a function simply by specifying
its name followed by a parenthetical list of arguments,
if any:
clearPage();
boldblink("Call me gaudy!");
Functions which return a result should be called from
within an expression:
total=raiseP(2,8);
if (raiseP(tax,2)<100) ...
Quite commonly, JavaScript functions are called from
within event handlers, which we'll take a look at later
in this article.
|