User Guide

Table Of Contents
174 Chapter 9: Writing and Calling User-Defined Functions
The following two statements are allowed only in function definitions:
A simple CFScript example
The following example function adds the two arguments and returns the result:
<cfscript>
function Sum(a,b) {
var sum = a + b;
return sum;
}
</cfscript>
In this example, a single line declares the function variable and uses an expression to set it to the
value to be returned. This function can be simplified so that it does not use a function variable, as
follows:
function MySum(a,b) {Return a + b;}
You must always use curly braces around the function definition body, even if it is a single
statement.
About creating functions using tags
You use the
cffunction tag to define a UDF in CFML. The cffunction tag syntax has the
following features and limitations:
Developers who have a background in CFML or HTML, but no scripting or programming
experience will be more familiar with the syntax.
You can include any ColdFusion tag in your function definition. Therefore, you can create a
function, for example, that accesses a database.
Statement Description
var variableName = expression; Creates and initializes a variable that is local to the function
(function variable). This variable has meaning only inside the
function and is not saved between calls to the function. It has
precedence in the function body over any variables with the same
name that exist in any other scopes. You never prefix a function
variable with a scope identifier, and the name cannot include
periods. The initial value of the variable is the result of evaluating
the expression. The expression can be any valid ColdFusion
expression, including a constant or even another UDF.
All
var statements must be at the top of the function declaration,
before any other statements. You must initialize all variables when
you declare them. You cannot use the same name for a function
variable and an argument.
Each var statement can initialize only one variable.
You should use the var statement to initialize all function-only
variables, including loop counters and temporary variables.
return expression; Evaluates expression (which can be a variable), returns its value to
the page that called the function, and exits the function. You can
return any ColdFusion variable type.