Understanding JavaScript Functions
JavaScript function provide a way to organize scripts and promote reuse. Rather than create longs sections of script scattered throughout an HTML page the script is instead organized into logical groups. JavaScript functions are simple to use, in fact you only need to do two things with a function, declare it and call it.
Declaring and Calling a JavaScript Function
The syntax of a JavaScript function is as follows:
function ''name'' ( ''argument1'', ''argument2'', ''argument3'' ... ) { ''statements'' return ''value'' }
The name specifies how we will refer to this function when we call it. The arguments specify values that are passed through to the function to be processed. The statements section represents the body of the function that performs the processing. The optional return statement allows a value to be returned the section of scripted that called the function (for example to return a status or the result of a calculation.
The following simple example shows a function defined in the <head> section of an HTML page and a call to this function in the <body>:
<html> <head> <title>A Simple JavaScript Function Example</title> <script language="JavaScript" type="text/javascript"> function sayHello() { alert("Hello!"); } </script> </head> <body> <script language="JavaScript" type="text/javascript"> sayHello(); </script> </body> </html>
Passing Arguments to a Function
The above example did not pass any arguments through to the function. Commonly a function is design to perform some task on a number of arguments as in the following example:
<html> <head> <title>A Simple JavaScript Function Example</title> <script language="JavaScript" type="text/javascript"> function sayHello() { alert("Hello!"); } </script> </head> <script language="JavaScript" type="text/javascript"> sayHello( "24th", "July" ); sayHello ( "1st", "August" ); sayHello ( "24th", "May" ); </script> </body> </html>
In this example the function is called multiple times, passing through arguments that are then used in the function to construct a string to be displayed in the alert dialog. To achieve this without functions it would ne necessary to repeat the script in the function 3 times over in the body. Clearly placing the script ina function and re-using it over and over is a much more efficient approach.
Next we need to look at how a function might return a value.
Returning a Value from a Function
The return statement is used to return a value from a function and the assignment (=) value is used to accept that return value at the point that the function is called.
As an exaqmple, we will declare a function that adds together two arguments and returns the result: