ColdFusion Functions

Some of the examples in previous lessons have included ColdFusion functions. Even though we've been using them in the examples, I haven't really explained what functions are and how you can use them. Well, that's about to change!

A function is a self contained block of code that performs a given 'function', then returns a value. Often, a function will require that you pass it one or more arguments. The purpose of an argument is to provide the function with further info that it needs in order to process. This info could be different depending on the context in which the function is being called.

You can either build your own functions, or use one of ColdFusion's built-in functions. ColdFusion has over 250 built-in functions ranging from string-manipulation functions, date functions, array functions, mathematical functions and many more.

To use a ColdFusion function, you write the function name, followed by opening/closing brackets. Any arguments that you pass to the function goes between the brackets.

Syntax

Example of Usage 1

You can simply output the results of a ColdFusion function by surrounding it with hash (#) signs and enclosing it within <cfoutput> tags.

The following function, RandRange(), returns a random number. We have supplied parameters 1 and 10 which tells it the random number must be between this range.

Display in browser:

3

Example of Usage 2

This example declares a variable called myRandomNumber and assigns its value using the RandRange() function.

Display in browser:

3

Nested Functions

You can nest one function inside another if required.

For example, let's say that you want to output the date to the user. You could use the Now() function for that, but it might not look the way you want it to...

Display in browser:

{ts '2017-12-12 04:17:29'}

Lets say you want to output the date in the following format: Mon 20 November, 2006

Well, in that case, you could nest the Now() function inside a DateFormat() function. The DateFormat() function allows you to pass parameters to determine the format.

Display in browser:

Tue 12 December, 2017

User Defined Functions

ColdFusion also provides the ability for you to create your own functions. There are two ways of doing this:

In the following lesson, we'll be using the <cffunction> tag within a ColdFusion component.