JavaScript Functions
In JavaScript, like other programming languages, functions are groups of
statements that are executed as a single unit. Before a function can be used,
it must be defined. The syntax for defining a JavaScript function is:
function functionName(parameters) {
statements;
}
They keyword function, followed by the function name and parameter list is
referred to as the function definition. The function name is a user-defined
value that must conform to the same rules used to name JavaScript variables.
Parameters are placed within the parentheses that follow a
function name. A parameter is simply a variable that is passed to the function
when it is called. Some functions contain multiple parameters, each separated by a
comma, while other functions contain no parameters at all. Functions that contain
no parameters perform tasks that do not require external data.
Following the function definition is a set of curly braces that contain the
function statements. The function statements do the actual work of the function
and must be contained within the braces. Semicolons should be included after each
of the function statements.
function addNumbers(firstNumber, secondNumber) {
var total = firstNumber + secondNumber;
}
Calling Functions
A function is run or executed when it is invoked or called from somewhere
in the JavaScript program. The code that calls a function is called a
function call. The function call includes the name of the function,
followed by parentheses that contain variables or arguments that
are passed to the called function. When a function is called, the values of the
arguements are assigned to the value of the corresponding parameter in the
function definition. A sample function call is shown below:
function addNumbers(firstNumber,secondNumber) {
var fotal = firstNumber + secondNumber;
}
addNumbers(number1,number2)
When the addNumbers() function is called, it passes two arguments - number1 and
number2 to the function. The value of argument number1 is passed to the parameter, firstNumber,
and the value of argument number2 is passed to the parameter, secondNumber. In some cases,
variables are declared within the function itself and not passed to the function.
Local Variables
Recall that JavaScript functions are the main processing entities in a script. It is inside
functions that variables are declared and their values are established and manipulated.
Variables that appear inside functions are local variables. This means that the variables
are "private" to those functions and are not accessible by other functions. The following
script, for example, contains two functions, process1() and process2(), which declare
the variables data1 and data2, respectively.
function process1() {
var data1 = 123.45;
process data1...
}
function process2() {
var data2 = 678.90;
process data2...
}
Variable data1 is local to function process1()
and is unknown by and is inaccessible by process2(). Likewise,
variable data2 is local to function process2()
and is unknown and inaccessible by process1(). Both variables are "hidden"
inside their respective functions. This means it would be perfectly valid to use the same variable
name for two different variables in two different functions. The variables are isolated within their
functions and would not be confused with each other. However, good programming practice is to use
different names for different variables in all cases. In this way, the programmer, at least, does
not become confused in keeping track of two different variables with the same name.
Passing Local Variables
In cases where complete and final processing of a variable can be accomplished
within a single function, this isolation of local variables does not raise access
issues. However, there may be occasion when a second function does need access to
a local variable of the first function. In this case, it is necessary for the first
function to call the second function and, at the same time, pass along its local
variable for access by the second function.
The general format for one function to call upon the processing of a second function
and to pass data values to the second function is shown in Figure 2-6.
function functionName1() {
functionName2(arugument1, argument2, ...);
...
}
A function makes a call to a different function through the latter's name.
In this case, the function call includes an argument list. That is, enclosed
in the paretheses of the function call is a list of one or more local
variables, separated by commas, which are made available to the called
function. These variable names, of course, represent the associated data
values that are stored in the variables and that are passed along to
the function.
On the receiving end, the called function gains access to the passed data
values. The general format for a function to capture data values passed
to it is shown below.
function functionName2(parameter1, parameter2, ...) {
process parameter1...
process parameter2...
...
}
The called function includes an parameter list. This is a list of one
or more variables local to the receiving function where the data values passed to it
are stored. The variable names assigned in the argument list do not have to match those
in the parameter list. However, the data values that are received are captured in the
order in which they are sent. That is, the first data value represented in the argument
list is stored in the first variable appearing in the parameter list; the second data
value in the argument list is stored in the second variable appearing in the parameter
list; and so on. There is one-to-one matching between the data values sent through the
argument list and the variables in which they are stored in the parameter list. Thereafter,
the receiving function can process the passed data values just as if they were local
variables, which they are.
Consider the following scenario. A function named Process1() declares local variable
MyLocalData. Apart from its own processing of this value, Process1() needs to call upon
function Process2() for addition processing of the variable. It calls Process2(),
passing along the MyLocalData value to make it available to this second function.
function process1() {
var myLocalData = 123.45;
...
process2(myLocalData);
}
function process2(passedData) {
process passedData...
}
Here, process1() calls the second function and, at the same time,
includes variable myLocalData in the argument list of the call:
process2(myLocalData). Keep in mind that only the data value stored
in the variable (123.45) is passed; the variable itself is not passed.
Function process2() receives the passed data value through its
parameter list: process2(passedData). Variable passedData is
where the passed value is stored. Now, process(2) can perform additional
processing on the value, stored locally as passedData.
Keep in mind that when a called function completes its processing, script control
returns to the calling function, and processing continues with the statement
following the function call. When the original function completes its
processing, the script ends.
Returning Values from Functions
Often times, functions are called, not to continue a sequence of processing tasks,
but to return a data value. A function, for instance, calls upon a second
function to manipulate passed data values. The result of this processing is
then returned to the calling function where processing continues with the
returned value. A called function returns a data value with a return statement
in the format shown in Figure 2-8.
function functionName(parameter1, parameter2, ...) {
...
return variable
}
Figure 2-8. Function returning a variable's value.
Suppose, for example, that a specialized function is created that multiplies
any two numbers passed to it. It then returns the product to the calling
function. Although you have not yet been introduced to JavaScript arithmetic
operations, you should be able to follow the logic of the following function
call and return.
function process1() {
var data1 = 10;
var data2 = 20;
var product = getProduct(data1, data2);
}
function getProduct(number1, number2) {
return number1 * number2;
}
process1() declares two local variables, data1 and
data2, and
assigns them numeric values. It also declares local variable product and
assigns it the value returned from a function call to getProduct(), passing
along the values of data1 and data2 in its argument list. getProduct() receives
the two values as number1 and number2 in its parameter list. It returns the
value of number1 multiplied by (*) number2 to the calling statement where it
is stored in variable product.
Using functions that return processed values plays a big role in JavaScript programming.
There are, in fact, many built-in functions that are part of the language and which
perform and return the results of complex processing that is commonly needed in
scripts, saving you the task of writing the required code. These built-in functions
are introduced as needed throughout the tutorials. Also, you will have occasion to
write your own functions to return values as situations dictate.
Global Variables
Sometimes two or more separate functions need access to the same variable
and it is not practical to pass it back and forth among the several functions.
In this case, the variable needs to be declared as a global variable.
A global variable is declared outside any functions. In the following example,
variable globalVariable is declared inside the JavaScript file, but not
inside either of the functions. Thereafter, globalVariable is directly
accessible by both functions.
var globalVariable;
function process1() {
process globalVariable...
}
function process2() {
process globalVariable...
}
It is normally considered good programming practice to isolate variables
inside functions, making them local variables, and explicitly passing them
between functions that need access to them. There is no risk that these
variables can be inadvertently corrupted by processing activities in other
functions that are not given explicit access to them. At times, though,
global variables can be used as a way to share their values among multiple
functions where convenience overrides the risks.
This section has focused on the development and use of user-defined JavaScript
functions. JavaScript also includes a number of built-in functions. These
built-in functions will be introduced throughout the tutorial.