4 - Javascript:Functions - Introduction
Introduction
Experience has shown that the best way to develop and maintain a large program
is to construct it from small, simple pieces, or modules. This
technique is called divide and conquer. In this class we'll
look at some features of JavaScript that facilitate the design, implementation,operation
and maintenance of large scripts.
Program Modules in JavaScript
Modules in JavaScript are called functions. JavaScript programs
are written by combining new functions that the programmer writes with "prepackaged"
functions and objects available in JavaScript. The prepackaged functions that
belong to JavaScript objects are often called methods. The
term method implies that the function belongs to a partricular object; however,
the terms function and method can be used interchangeably. We will refer to
functions that belong to a particular JavaScript object as methods; all others
are referred to as functions.
Functions
A function contains some code that will be executed by an event or a call
to that function. A function is a set of statements. You can reuse functions
within the same script, or in other documents. You define functions at the beginning
of a file (in the head section), and call them later in the document. By placing
functions in the head section of the document, you make sure that all the code
in the function has been loaded before the function is called. It is now time
to take a lesson about the alert-box:
This is JavaScript's built-in method to alert the user.
alert("This is a message")
How to Define a Function
To create a function you define its name, any values ("arguments")
if any, and some statements:
A function with no arguments must include the parentheses:
function myfunction()
{
some statements
}
Arguments are variables used in the function. The variable values are values passed on by the function call.
Some functions return a value to the calling expression
function result(a,b)
{
c=a+b
return c
}
How to Call a Function
A function is not executed before it is called. So you can enter it into the
head of the page and it will just sit there, waiting for some action to trigger
it.
You can call a function containing arguments:
myfunction(argument1,argument2,etc)
or without arguments:
myfunction()
The return statement
Functions that will return a result must use the "return"
statement. This statement specifies the value which will be returned
to where the function was called from. Say you have a function that returns
the sum of two numbers:
function total(a,b)
{
result=a+b
return result
}
When you call this function you must send two arguments with it:
sum=total(2,3)
The returned value from the function (5) will be stored in the variable called sum.
If you don't send the proper number or type of arguments, you'll get a script error.