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
    Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
    The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
    The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
    We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
    The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
    There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
    Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
    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...
    Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
    BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.