Using functions as operators

Functions are a form of operator. Because ColdFusion functions return values, you can use function results as operands. Function arguments are expressions. For example, the following are valid expressions:

  • Rand()

  • UCase("This is a text: ") & ToString(123 + 456)

Function syntax

The following table shows function syntax and usage guidelines:

Usage

Example

No arguments

Function()

Basic format

Function(Data)

Nested functions

Function1(Function2(Data))

Multiple arguments

Function(Data1, Data2, Data3)

String arguments

Function('This is a demo')

Function('This is a demo')

Arguments that are expressions

Function1(X*Y, Function2("Text"))

All functions return values. In the following example, the cfset tag sets a variable to the value returned by the Now function:

<cfset myDate = DateFormat(Now(), "mmmm d, yyyy")>

You can use the values returned by functions directly to create more complex expressions, as in the following example:

Abs(Myvar)/Round(3.14159)

For more information on how to insert functions in expressions, see Using number signs.

Optional function arguments

Some functions take optional arguments after their required arguments. If omitted, all optional arguments default to a predefined value. For example:

  • Replace("Eat and Eat", "Eat", "Drink") returns "Drink and Eat"

  • Replace("Eat and Eat", "Eat", "Drink", "All") returns "Drink and Drink"

The difference in the results is because the Replace function takes an optional fourth argument that specifies the scope of replacement. The default value is “One,” which explains why only the first occurrence of “Eat” was replaced with “Drink” in the first example. In the second example, a fourth argument causes the function to replace all occurrences of “Eat” with “Drink”.

Expression evaluation and functions

It is important to remember that ColdFusion evaluates function attributes as expressions before it executes the function. As a result, you can use any ColdFusion expression as a function attribute. For example, consider the following lines:

<cfset firstVariable = "we all need"> 
<cfset myStringVar = UCase(firstVariable & " more sleep!")>

When ColdFusion server executes the second line, it does the following:

  1. Identifies an expression with a string concatenation.

  2. Evaluates the firstVariable variable as the string "we all need".

  3. Concatenates "we all need" with the string "more sleep!" to get "we all need more sleep!".

  4. Passes the string "we all need more sleep!" to the UCase function.

  5. Executes the UCase function on the string argument "we all need more sleep!" to get "WE ALL NEED MORE SLEEP!".

  6. Assigns the string value "WE ALL NEED MORE SLEEP!" to the variable myStringVar.

ColdFusion completes steps 1-3 before running the function.