August 11, 2006
JavaScript Functions 101
A function is a self-contained block of statements. Functions are very good at holding reusable code. You can declare a function by using the function keyword followed by the name of the function you want to create:
function myfunction() { // do something }
You execute the function like this:
myfunction();
Declarative Function
The parentheses are there to take arguments. Arguments are values that you can pass to a function. Within the function, they act just like variables.
When you create a function, you can specify how many arguments it takes in a comma-separated list. Here is an example of a function that takes two arguments:
function multiply(x,y) { var result = x * y; return result; }
The multiply function takes the arguments x and y, and multiplies them together. As well as accepting values, this function is returning a value at the end using a return statement. A function doesn't have to return a value, but if it does, you can assign, you can assign the result of a function to a variable:
var days_old = multiply (35, 365);
Function Literal
A function is actually a kind of variable. Suppose you have a function that you have declared like this:
function shout() { alert( "Hey!" ); }
You could use a var statement to achieve the same result:
var shout = function() { alert( "Hey" ); };
The function is still executed the same way:
shout();
If you want to refer to a function without executing it, treat it like any other variable and don't include the parentheses:
var annoy = shout
Now the variable annoy is a reference to the function shout. The variable annoy is effectively a synonym for shout and can be executed that same way:
annoy();
Anonymous Function
If you include those parentheses when you assign a function to a variable, JavaScript will assume that you want to assign the result of the function to the variable. So you can't include the parentheses when you’re storing a reference to a function.
But what if you want to store a reference to a function with an argument?
The solution is to wrap the shout function in an empty function:
var annoy = function() { shout ( "Hey" ); };
This is called an anonymous function and is very useful for assigning functions to event handlers (i.e. windows.onload).
For a more detailed information about JavaScript functions checkout this excerpt on functions (.pdf) on functions from JavaScript: The Definitive Guide, Fifth Edition book by David Flanagan.
