ColdFusion Variables

Variables are a standard part of any programming language. A variable can be visualised as a container that stores a value.

We can use variables in many circumstances. For example, we could store the user's name inside a variable. We could then present the user's on the web page they're visiting. We could also perform a test against the variable to see what the value is. The application could then perform a different action depending on the value of the variable.

Using cfset

Syntax

To set a ColdFusion variable, use the <cfset> tag. To output the variable, you need to surround the variable name with hash (#) symbols and enclose it within <cfoutput> tags.

Example of Usage

This example uses the <cfset> tag to declare a variable called firstname and assign a value of bono to it. It then outputs the contents of the variable.

ColdFusion code:

Display in browser:

Hello Bono.

Using cfparam

The <cfparam> tag creates a variable if it doesn't already exist. You can assign a default value using the default attribute. This can be handy if you want to create a variable, but don't want to overwrite it if it has already been created elsewhere.

Example 1

In this example, the variable hasn't been set previously, so it will be assigned with the <cfparam> tag.

This results in the following:

Hello Ozzy

Example 2

In this example, the variable has already been assigned (using the <cfset> tag), so this value will override the default value in the <cfparam> tag.

This results in the following:

Hello Barney

Checking if a Variable Exists

You can check if a variable has been defined or not by using ColdFusion's built in IsDefined() function. This can be used inside a <cfif> tag to prevent nasty error messages in the event you attempt to refer to a variable that doesn't exists. You could also use this function to determine whether a user has performed a certain action or not.