Account Log In - Home/Outlines - Books - Contact Us - Support - Employment -

DHTML

JavaScript Programming Fundamentals

Functions

Functions are a great way to help you write more economical JavaScript code. Scripts that make good use of functions are capable of doing far more than scripts that don't. As you will see in this lecture, functions are a great thing to know how to use.

What is a Function?

A function is basically like a bit of self contained code within a script. In form, it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces. A function can either carry out an action (or set of actions), return a value, or both. Good functions can be re-used over and over again. They can be thought of as building blocks that can be used in numerous other scripts.

Functions take the following form:

function myFunction(parameters) {
   statements contained within the function;
}

Some notes about the above form

Functions can contain any JavaScript statements that you wish to put in them. Functions should usually be as small as possible. There is no size restriction to a function, but they are easier to keep track of if you keep them small and focused in their purpose.

Here is an example of one of our earlier scripts that checked for an @ symbol and returned either a -1 or its position in the string.

function checkEmail() {

   var email_addy = prompt('Please enter your email address','');
   var is_email = email_addy.indexOf('@');
   alert(is_email);

}

Notice that the function contents are indented the same way that we indented conditionals and loops earlier. This is good coding practice as it makes your code easier to read and understand.

Why use Functions?

Aside from what we mentioned above about the ability to re-use functions over and over again within a script, or to use them to help build other scripts, functions have other merits.

All of the scripts we have shown you so far will run as soon as the page loads. If they are in the <head> section, they will run before the <body> of the page loads, and if they are in the <body> section, they will run after any HTML that is above them. This doesn't do us much good if we only want our script to run after user interaction, or some other kind of event.

A function, even if it is in the <head> section of the page, (and that is usually the best place to put it) will not run when the page loads. It will only run after it is called.

Calling Functions

A function will only run when it is asked to. This is referred to as calling a function. Functions are commonly called from within event handlers (remember those?), but functions can also be called from other areas of the script, including other functions.

Calling a Function From a Script

A function is called within a script by writing its name, followed by parentheses, with or without parameters. We will first look at functions without parameters, for simplicity's sake.

alert('we need to check to see where the @ symbol is at');

//Call the function
checkEmail();

If we are assuming this is a separate script from the one above (and we are), then we don't need to include the function itself in this script. It can be called from anywhere on the page. Once again, not only can a function be called from inside a script, it can also be called from inside another function.

Calling a Function With an Event Handler

One of the more common ways to call a function is with an event handler. Such an event handler could look something like this:

<a href = "#" onclick = "swapImage(); return false;">Click to see an image change</a>

In this case, the event handler onclick will call the function swapImage().

A function can also be called without user interaction when the page loads by using the onload event handler:

<body onload = "loadImages();">

Passing Variables

You can pass variables to functions from other areas of the page. This is done using the function's parameters. Here's how this is done. Let's start with the event handler:

<a href = "#" onclick="varPassTest('Tom', 'Dick', 'Harry'); return false;">Click to pass some variables to a function</a>

As you can see, we placed three text strings, separated by commas, between the parentheses of the function call. Here's the function:

function varPassTest(name1, name2, name3) {

    alert(name1 + name2 + name3);

}

When you click on the link that contains the event handler, the three values are passed to the function. The function itself has three parameters, name1, name2, and name3. The only thing contained within the function itself is an alert box that will display all three variables. (Note: you don't need to initialize these variables with the var statement, as the are already automatically initialized when used this way. )

Just to show you how this works, we've set up an example that uses two event handlers to pass off two different sets of values, but uses the exact same function.

Returning Values

We already know how functions can have variables passed to them through their parameters, but functions can do something else: they can return values.

This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input. The script inside the <body> of the document will ask you for the number and print out the result. The function is contained in the <head> section.

Here is the body script:

// Prompt the user for a number.
var initial_number = prompt('Please type in a number','');

// Call the function, and pass it initial_number for processing.
fixed_number = addDollar(initial_number);

// take the number the function returned and write it out.
document.write('This is your number converted to a dollar amount: ' + fixed_number);

Here is the function in the <head> script.

function addDollar(num) {

    // add the dollar sign before the number, and .00 after.
    new_number = '$' + num + '.00';

    // return the num variable back out of the function.
    return new_number;

}

Here is an example of the above script

Let's talk about what happens in these scripts.

  1. The user is prompted for a number, which is assigned to the initial_number variable.
  2. initial_number gets passed to the function addDollar.
  3. Once in the function, the value of initial_number is assigned to the function's parameter, num.
  4. new_number is given the value of num with a dollar ($) character before it, and a period and two dots after.
  5. The statement return new_number; returns the value of new_number back out of the function.
  6. The returned variable is assigned to fixed_number.
  7. fixed_number is printed out on the screen.

This function we just created can be used again and again in this document, and in turn re-used later on in other scripts and documents if you like. It is singular in its purpose, which is to turn any number passed to it into a dollar amount.

Local And Global Variables

Now what we have talked about functions, we can talk about how variables work within them. You have already seen how variables that are passed to the function using its parameters work, and how these don't require the var statement.

When you initialize variables in your script as we have been doing all along (outside a function), these are called global variables. They can be referenced from anywhere on the page, regardless of whether they are in another script or not.

When you initialize variables inside a function with the var statement (not with the function parameters), these are called local variables. They can only be referenced inside the function itself. So if you know you will only use a variable from within the function itself, initialize them there. However, if you want to be able to use a variable anywhere on the page, initialize it in the script, outside of a function.

Functions Summary

Coming Soon:

Feb 13
ISSD 24 - XML
Feb 14
Web Design Level 4: XHTML Advanced
Feb 21
ISSD 23 - Web 2.0 Technology
Feb 23
Facebook for Business
Hours: 2
Cost: Free!
Feb 25
Search Engine Optimization (SEO)
Hours: 2
Cost: Free!
Feb 25
Search Engine Marketing (SEM)
Hours: 2
Cost: Free!
Feb 27
ISSD 24 - OLDB (Online Databases with MySQL and PHP)
Mar 05
ISSD 23 - Ajax
Mar 20
Web Design Level 5: DHTML Introduction


DHTML - TOC - Introduction - Books -
JavaScript Programming Fundamentals - Links - Questions -
1 - 2 - 3 - 4 - 5 - 6 - 7 - [ 8 ] - 9 -

DHTML - TOC - Introduction - Books -
JavaScript Programming Fundamentals - Links - Questions -
1 - 2 - 3 - 4 - 5 - 6 - 7 - [ 8 ] - 9 -