As well as library functions, JavaScript allows you to create your own functions.
Functions provide a way to group JavaScript statements into blocks that are reusable - making for more compact code and easier maintenance.
Functions are first defined then called from within the script in the same way as library functions. Functions can be defined anywhere within a script but it's normal to define them at the start.
A function may have no arguments (sometimes called parameters) or it may have many. A Function may also return arguments.
Defining a Function
A function begins with the word function followed by a unique name for the function.
The name is followed by opening and closing parenthesis with arguments, separated by commas, inside - if there are any.
This is followed with an opening brace then the JavaScript statements that make up the body of the function
A closing brace is used to end the function definition
Example of a function() Definition
<script language="javascript" type="text/javascript">
function highlight (text)
{
text = "<b><i>"+text.toUpperCase()+"</i></b>";
document.write(text);
}
this_string = "warning";
// This prints out WARNING in bold italic
highlight (this_string);
</script>
JavaScript makes no check on the data types passed as arguments to a function so it's up to the programmer to ensure that they match - if that's important.
Also no check is made on the number of arguments passed. If less are passed than required then the missing ones will be considered undefined. Excess arguments are just ignored.
Returning Values
A function can use the return statement to pass back values as in the example below.
Example of Returning a Value
<script language="javascript" type="text/javascript">
function add (number_1, number_2)
{
result = number_1 + number_2;
return (result);
}
// This prints out 8
document.write (add (5, 3));
</script>
Variable Scope
When a variable is created, its value is not automatically available at every point in the programme.
There is a relationship between where it is created and where it can be used. This relationship is called the variable's scope.
When a variable is created inside a function it is a local variable and only has scope inside the function. It only exists when the function is called and is discarded when the function ends.
An Example of Scope
<script language="javascript" type="text/javascript">
function showscope ()
{
var variablescope = "Local";
document.write (variablescope);
}
var variablescope = "Global";
// This prints out Local as you'd expect
showscope ();
/* This prints out Global because variablescope created
inside the function is different to variablescope
outside the function */
document.write (variablescope);
</script>
The same is true for function arguments. They are local and only have scope within the function.
// This prints out Local as you'd expect
showscope (variablescope);
/* This prints out Global because the function
was only passed a copy of variablescope so variablescope
has not been changed by the function */
document.write (variablescope);
</script>
If a variable is passed to a function or created inside a function then even if it has the same name as a variable outside the function it isn't the same variable.
Global Variables
A variable inside a function with the same name as a variable outside the function IS global if it has neither been created (i.e. declared) inside the function nor passed to the function.
// This prints out Local as you'd expect
showscope ();
/* This also prints out Local because the function wasn't passed
a copy of variablescope nor was variablescope created inside
the function so variablescope has been changed */
document.write (variablescope);
</script>
This is a good reason for always properly declaring variables using the var keyword when you create them.
If you don't stick to this habit you may end up with bugs that can be very difficult to trace.
Note: When you give a function the right to alter a global variable you pass a lot of power to the function so you should only do so when absolutely necessary.
If lots of functions are allowed to alter a global variable in a large programme, it can be very difficult to remember which functions are changing the variable.
The Function() Constructor
As well as using the function keyword to create a function, you can also use the Function() constructor along with the new operator.
This does essentially the same thing but with a couple of differences.
A function can be created dynamically depending on set conditions. This means however that the function has to be compiled each time it's called - instead of just once.
The function can be defined as part of an expression instead of as a statement.
The Function() constructor takes any number of string arguments. The last string argument is made up of the JavaScript statements, separated with semicolons, that will form the body of the function.
Any string arguments before the last string argument are treated as the names of the arguments that the function will use.
The Function() constructor does not require the name of the function as an argument since the function is defined like a variable and given a name.
Example of Using the Function() Constructor
<script language="javascript" type="text/javascript">
var add = new Function ("number_1", "number_2", "result = number_1 + number_2;return (result);");
// This prints out 8
document.write (add (5, 3));
</script>
Using Functions as Data
When a function is given a name it can be thought of as a variable that holds the function.
And in the same way that a variable may be set to equal another variable then a function may be assigned to another variable.
Example of a Function as Data
<script language="javascript" type="text/javascript">
function add (number_1, number_2)
{
result = number_1 + number_2;
return (result);
}
// Assign function add() to variable compute
var compute = add(5, 3);
// This prints out 8
document.write (compute);
</script>
Functions may also be assigned to object properties and when they are they are known as methods (covered in the Objects.Properties.Methods Tutorial).
Example of Creating a Method
<script language="javascript" type="text/javascript">
// Create an object called numbers
var numbers = new Object();
// Add a method called add to the object
numbers.add = new Function ("number_1", "number_2", "result = number_1 + number_2;return (result);");
// Assign the object to a variable called sum
var sum = numbers.add (5, 3);
// This prints out 8
document.write (sum);
</script>