WbWizard's JS Book

Blue Line

Lesson 6: Functions

Today we will begin discussing the main programming tool of JavaScript, the function. We will discuss what a function is, how to write a function, and cover some ways to use a function. We will save discussions about the "prototype" property of functions for a future thread dealing with how to define objects and their properties, but we will discuss the syntax need to construct functions as objects here.

1) Function Definition and Syntax
The function statement of JavaScript defines an executable block of code using this syntax:

function _Function_Name(_Function_Args){
return _Function_Return_Value;

Always begin a function definition with the word "function", then a single space, then the name of the function (which can be any non-reserved word or combination of alpha-numeric characters [a-z-0-9]), a set of parenthesis containing any arguments (data being passed to the function) seperated by commas, an opening curly bracket, lines of JavaScript coding separated by semicolons which make up the body of the function, including an optional return statement which stops the function (even if there is more to the function) and sends back a specified value (if no return statement is used, the function returns undefined by default), and a closing curly bracket to end the function statement.

Example, here is a function that receives a number and returns the square of that number:

function squareIt(x){
return x;

Now, since JavaScript is an untyped language, it does not automatically check for the correct data type in the argument values, and so errors may occur in cases where auto type conversion does not occur and data types do not match. You can check for data types yourself using the typeof variable check.

2) Function Constructor
Functions can also be defined using the "new" operator to "construct" a new object containing the function. This technique allows for the creation of classes of functions which can be utilized in various ways in complex programming (more on this in later threads). To create a new function, we use the following syntax (notice it contains the same data as the function definition, but the syntax creates an object which will have it's own properties and methods):

var squareIt=new Function("x","x=x*x;return x;")

Arguments are each contained in quotes and seperated by a comma, and the final set of quotes seperated from the arguments by another comma contains the entire list of JavaScript codes seperated by semicolons.
[Note-if you do not name the function, and instead merely invoke the new Function(); method with no variable name, the name anonymous may be used as the name of the function on some platforms, giving functions created in this method the general name "anonymous functions".]

3) Functions as Data

One of the great advantages to JavaScript being an untyped language is that functions (among other things) can be treated as data without type conversion or complex variable data typing. What this means is you can treat a call to a function as a variable or chunk of data in your normal execution of coding. For example, the above squareIt() function can be treated as a variable of the value of it's arguments after execution of it's code body, at the time of use. In a type language like C or Java, all values would have to be used as specific data types, converted through specific algorithgms to alternative data types of equivalent value, then stored in variables set to this data type, then compared and finally used in a computation. Thank God and JavaScript we have it much easier! :-)

Example, to obtain the length of the long side of a triangle (hypotenuse), you need to perform the squareIt() function on two variables, the length of the two shorter sides of the triangle. You can use the function call as a variable representing the return value of the function thanks to JavaScript's untyped language charachteristics:

function hypotenuse(a,b){ z=Math.sqrt(squareIt(a)+squareIt(b)); return z; }

You can also use functions within computations and within calls to themselves and or other functions, or within any data structure such as arrays.

a=new Array();
a[0]=function(x){x=x*x;return x;};

In this example, a[0] is set to a function that computes the square of a value, a[1] contains a value, and a[2] is set to a value computed by the function in a[0] using the value stored in a[1]. So a[2] is equal to the evaluation of a function stored in the same array which is passed an argument value stored in the same array, and it's vaule is 25.

4) Functions For Repetition Perhaps the most appealing thing about functions is their ability to handle the same computation with various data values, and do it over and over with only one block of coding. This allows us to for instance create a single function to replace a status bar message we used onMouseOver on a link, after the highlight box is moved away from the link (onMouseOut) preventing the message from remaining there.
Rather than write onMouseOut="status='DEFAULT_MESSAGE';" over and over in each link that uses a onMouseOver status message, we can write a function and place only the call to that function in the onMouseOut event handler:

Calculations, messages, interactions, almost anything of a repetitive nature can be handled in a function, allowing scripting to be concentrated in a single script section with calls in event hanlders (modular).

Sample 6- Multiple Function Syntax Use

Easy Pad

Blue Line
Lessons by
Jerry aka WebWizard