Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Expressing Yourself in ColdFusion

Using expressions to process data

Hello and welcome to the second installment of CF101. Last month I talked about variables in ColdFusion and how to create them using the <cfset> tag. I also showed you how to display the value of a variable using the <cfoutput> tag and a ColdFusion expression. I decided to leave an in-depth discussion of ColdFusion expressions to another time. That time is now.

Expressions Explained
You can use an expression to tell your CFML engine to process some data. A simple expression can be made up of a single element, called an operand. A complex expression is made up of multiple operands strung together with an operator. I'll discuss complex expressions a bit later.

The simplest expression is a single operand. There are many different types of operands that can be used in a ColdFusion expression. Here are some of the different elements:

  • Literals: A literal value is a hard-coded value. Any of the simple data types, such as integers, real numbers, strings, dates, or Booleans, can be accepted as a literal value. Strings or dates are always enclosed in quotes (single or double). Quotes are not required for numeric literals. Boolean values are "Yes" and "No", "True" and "False", and any number and 0. Surrounding the value with quotes is optional with all but "Yes" and "No".
  • Variables: Variables can be used as an expression. When a variable is used, the value of the variable is returned. A variable can contain a simple value such as a number or a string, or a complex value such as an array or structure.
  • Functions: Any of ColdFusion's built-in functions can be used as a ColdFusion expression. With over 250 built-in functions, you can do a lot. I'll save the discussion of functions in CFML for another day. You can read more about ColdFusion's functions at http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/function.htm.

    Let's look at an example to see how expressions are used.

    Putting an Expression to Use
    You may remember from last month that I said the <cfset> is used in this format:

    <cfset variableName = value>

    However, this is actually a simplified version. The value portion of the tag is actually an expression. The following would be a more accurate description of the <cfset> tag:

    <cfset variableName = expression>

    Look at the following examples:

    <cfset FirstName = "Jeffry">
    <cfset LastName = "Houser">
    <cfset Age = 28>
    <cfset FName = FirstName>

    Four variables are created with this segment of code. The first two lines create variables, FirstName and LastName, that contain string values. The value of each variable is a literal expression, with the value being a string. The third line creates a variable called Age using a numeric literal expression. The fourth line creates a variable called FName. Here our expression is a variable, not a literal value.

    What can be done with the variables once they are created? The simplest example is to display them, using the <cfoutput> tag.

    <cfoutput>
    #FirstName#<br>
    #LastName#<br>
    #Age#<br>
    #FName#<br>
    </cfoutput>

    The code starts with the <cfoutput> tag. Then comes an expression that displays the value in the FirstName variable. The expression is followed by an HTML line break. Then comes an expression that displays the LastName variable, and another line break. Third, an expression displays the age variable. Are you noticing a pattern yet?

    The <cfoutput> tag block contains ColdFusion expressions and HTML. The pound signs allow the CFML server to tell the difference between expressions and plain text or HTML. The expressions are evaluated and the results are returned to the browser. The resulting browser display will look something like this:

    Jeffry
    Houser
    28
    Jeffry

    Both code segments will have to be put in the same template to correctly display the output. If you've had any experience with ColdFusion before reading this article, you have probably already been exposed to expressions.

    Pounding the CFML Pavement
    As you examine the two code segments presented earlier, you'll probably notice that inside the <cfoutput> block we delimit the ColdFusion expressions using the pound sign, yet do not use any pound signs inside the <cfset> tags. Why is this? The pound sign is not needed inside as part of a ColdFusion tag such as <cfset>. You could write the <cfset> code segment with all the expressions in pound signs, like this:

    <cfset #FirstName# = #"Jeffry"#>
    <cfset #LastName# = #"Houser"#>
    <cfset #Age# = 28>
    <cfset #FName# = #FirstName#>

    However, it is generally not considered good practice to do so. Specifying the pound signs means that your CF Server has to do more work, thus resulting in code that is less efficient than it could be. All those pound signs can also make the code more confusing to read. You don't usually need to use the pound sign if your expression is inside a ColdFusion tag or function. So when do you? A good rule of thumb is that if you're inside quotes you probably need pound signs, otherwise you probably don't (there are a few exceptions to this rule - like isDefined(), which takes a variable name as a string inside quotes).

    So, if the pound signs aren't needed inside ColdFusion tags or functions, why are they needed in the <cfoutput> tag block? In <cfset> you're using the expression as part of the tag and it is safe to assume you are creating ColdFusion expressions. In the <cfoutput> block the expression is not part of the tag, only part of the text between the open and close tag. ColdFusion needs a way to distinguish between the two, and that is the reason for the pound signs. In most cases you can use pound signs only around simple expressions. To output the value of a complex expression, store the result to a variable and output the variable using a simple expression.

    If you are creating a dynamic variable name using <cfset>, you'll need to use pound signs. Dynamic variable naming is beyond the scope of this article, but more information can be found at http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/exprea24.htm. You may also need to use pound signs if you want to display the value of a variable inside a string literal (which is when you're inside quotes). More information on this can be found at http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/exprea16.htm. You specify the attributes of many CFML tags as strings. When using them, I find it a good practice to ask myself whether I'm referencing a variable or a string. As mentioned earlier, if it's a variable, then use pound signs. Otherwise, specify the literal value without pound signs.

    Using Operators to Create Complex Expressions
    All of the expressions we've looked at up to this point have been simple expressions. Simple expressions can be tied together with one or more operators to form complex expressions. The format of an expression would be something like this:

    Expression Operator Expression

    It is worth noting that each expression can contain another expression, thus creating very complex expressions.

    Operators fall into four main types: arithmetic, strings, decision, and Boolean. Arithmetic operators are used to perform math functions; string operators are used to combine multiple strings into a single string; decision operators are used to produce Boolean values based on the results of a comparison; and Boolean operators are used to perform logical operations. I'll save a discussion of Boolean and decision operators for the next column. Here are some of the more commonly used string and arithmetic operators:

    • +: The plus operator is an arithmetic operator used to perform addition of two numbers. The plus operator can also be used as a unary operator to define a number as a positive number.
    • -: The minus operator is an arithmetic operator used to perform subtraction of two numbers. The minus operator can also be used as a unary operator to define a number as a negative number.
    • *: The multiplication operator is an arithmetic operator used to multiply two numbers together.
    • /: The division operator is an arithmetic operator used to divide a number by a second number.
    • MOD: The mod command is an arithmetic operator that will divide a number by a second number and return the integer remainder.
    • \: The \ is an arithmetic div operator. It divides a number by a second number and returns an integer result without a remainder.
    • ^: The caret symbol is an arithmetic operator used to define the exponents of a number (to raise a number to a power).
    • &: The ampersand operator is the only string operator. It is used to concatenate two strings together. The second string is placed at the end of the first string and the result is returned as a single string.
    With all these operators, you will need to know the order of operations. Thankfully, the order of operations that ColdFusion uses is very similar to the one you probably learned in an elementary math class. First, the unary + and unary - operators are applied to specify which numbers are positive and which are negative. After the unary operators, the exponent symbol is evaluated. Next multiplication and division are performed, from left to right. Then the div operator is executed. Next comes the MOD operator. Following that, the subtraction and addition operators are applied from left to right. The string concatenation operator comes next, followed by all the decision and Boolean operators that are beyond the scope of this article. Normally you wouldn't want to mix string and arithmetic operators, but it is possible. Just as in math class, you can control the order of operations using parentheses, and evaluation always begins with the innermost set when parentheses are nested.

    Examples of Complex Expressions
    Here is an example of some complex expressions in action:

    <cfset FirstName = "Jeffry">
    <cfset LastName = "Houser">
    <cfset FName = FirstName & LastName>
    <cfset Age = 27+1>

    The code starts out simply by setting two variables, FirstName and LastName. Both of these lines use simple expressions. The next line is more interesting. It creates a variable called FName by concatenating the FirstName variable with the LastName variable. The final piece of code uses the addition operator to add two numbers together. We can display these values using this code:

    <cfoutput>
    #FName#<br>
    #Age#<br>
    </cfoutput>

    The display code should be familiar to you based on our other examples. We have a <cfoutput> block and a mix of CFML expressions and HTML line breaks. If you put both code segments into a browser and execute the code, you should see something like this:

    JeffryHouser
    28

    But wait. Maybe you don't want to butt the FirstName and LastName up against each other. We can use a string literal and the concatenation operator to modify the <cfset> tag to add a space between the two in the FName value. Replace the third line of cfset code with this:

    <cfset FName = FirstName & " " & LastName>

    Then when you execute the display code you will see the full name correctly separated.

    Conclusion
    Expressions are an important part of ColdFusion development. Next month we'll take a look at making decisions in your code using the <cfif> tag. That article will also include an examination of Boolean and decision operators.

  • More Stories By Jeffry Houser

    Jeffry is a technical entrepreneur with over 10 years of making the web work for you. Lately Jeffry has been cooped up in his cave building the first in a line of easy to use interface components for Flex Developers at www.flextras.com . He has a Computer Science degree from the days before business met the Internet and owns DotComIt, an Adobe Solutions Partner specializing in Rich Internet Applications. Jeffry is an Adobe Community Expert and produces The Flex Show, a podcast that includes expert interviews and screencast tutorials. Jeffry is also co-manager of the Hartford CT Adobe User Group, author of three ColdFusion books and over 30 articles, and has spoken at various events all over the US. In his spare time he is a musician, old school adventure game aficionado, and recording engineer. He also owns a Wii. You can read his blog at www.jeffryhouser.com, check out his podcast at www.theflexshow.com or check out his company at www.dot-com-it.com.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    IoT & Smart Cities Stories
    Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Japan DX Pavilion at @CloudEXPO Silicon Valley
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
    The graph represents a network of 1,329 Twitter users whose recent tweets contained "#DevOps", or who were replied to or mentioned in those tweets, taken from a data set limited to a maximum of 18,000 tweets. The network was obtained from Twitter on Thursday, 10 January 2019 at 23:50 UTC. The tweets in the network were tweeted over the 7-hour, 6-minute period from Thursday, 10 January 2019 at 16:29 UTC to Thursday, 10 January 2019 at 23:36 UTC. Additional tweets that were mentioned in this...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Where many organizations get into trouble, however, is that they try to have a broad and deep knowledge in each of these areas. This is a huge blow to an organization's productivity. By automating or outsourcing some of these pieces, such as databases, infrastructure, and networks, your team can instead focus on development, testing, and deployment. Further, organizations that focus their attention on these areas can eventually move to a test-driven development structure that condenses several l...
    The term "digital transformation" (DX) is being used by everyone for just about any company initiative that involves technology, the web, ecommerce, software, or even customer experience. While the term has certainly turned into a buzzword with a lot of hype, the transition to a more connected, digital world is real and comes with real challenges. In his opening keynote, Four Essentials To Become DX Hero Status Now, Jonathan Hoppe, Co-Founder and CTO of Total Uptime Technologies, shared that ...
    Over the course of two days, in addition to insightful conversations and presentations delving into the industry's current pressing challenges, there was considerable buzz about digital transformation and how it is enabling global enterprises to accelerate business growth. Blockchain has been a term that people hear but don't quite understand. The most common myths about blockchain include the assumption that it is private, or that there is only one blockchain, and the idea that blockchain is...
    Never mind that we might not know what the future holds for cryptocurrencies and how much values will fluctuate or even how the process of mining a coin could cost as much as the value of the coin itself - cryptocurrency mining is a hot industry and shows no signs of slowing down. However, energy consumption to mine cryptocurrency is one of the biggest issues facing this industry. Burning huge amounts of electricity isn't incidental to cryptocurrency, it's basically embedded in the core of "mini...