CFSCRIPT Intro
An Introduction to CFSCRIPT

We all know and love ColdFusion for its easy to use tag-based syntax. So why is there even a cfscript-style syntax? Well, there are a couple of reasons:
  • some CFers are already proficient in other langauges, and may feel more comfortable writing program events in a more 'traditional' method.
  • some people think that cfscript style syntax is easier to read (more straightforward).
  • cfscript exectues faster than a comparable block of tag-based code (i've heard this is even more true in MX).
So what does all of this mean to you? Do you have to use cfscript? Absolutely not. But given the advanatges mentioned above (as well as the ability to more easily write User-Defined Functions in CF 5 and above), you may want to check out cfscript to see what it can do for you.


'Rules' of CFSCRIPT
  • Place cfscript code within <cfscript></cfscript> tags.
  • No ColdFusion tags can be used in cfscript blocks. Only ColdFusion functions.
  • All lines must be terminated with a semi-colon (;).
  • While CFSCRIPT shares many characteristics with other scripting languages such as JavaScript, it is still ColdFusion, which means ColdFusion rules/syntax still apply:
    • Arrays start at position 1 (as opposed to 0)
    • Use the EQ, NEQ, LT, GT (etc) comparison operators (as opposed to =, !=, <, >, etc)
    • The ampersand (&) is the concatenation character (as opposed to the plus (+) character).
    • CFSCRIPT is case-insensitive...but I always recommend trying to watch your cases in order to promote good programming habits

CFSCRIPT Syntax

Ok...that's all well and good. But what does it LOOK like? Fair enough. Let's start very simple. Setting a variable.

<cfscript>
     myName = 'Charlie';
</cfscript>

Not so terrible, eh? :) You can even use CFSCRIPT to output your values:

<cfscript>
     myName = 'Charlie';
     writeOutput('my name is ' & myName);
</cfscript>

Excellent. You are well on your way :)

How about looping? Is there looping in CFSCRIPT? You bet your bippy there is ($5 to anyone who can tell me what a bippy is, by the way...i've always wondered).


Looping in CFSCRIPT

1.   <cfscript>
2.        myList = 'George,Paul,John,Ringo'; // creates the variable myList, which holds 4 names
3.        for (i = 1; i LTE listLen(myList); i = i+1) {
4.             writeOutput(listGetAt(myList, i) & "<br>");
5.        }
6.   </cfscript>

Let's go over this line by line, shall we?
(audience responds in unison, 'we shall')
Great.

1.   Opening our <cfscript> block
2.   create a variable called myList. Populate with 4 names (George,Paul,John,Ringo). You'll also notice the comment (the // and the text after it). This is a standard single-line script comment (similar in 'regular' CFML to <!--- comment --->). You can also do a multi-line comment, such as:
/*
This is a multi-line comment.
anything within the slash/asterisk - asterisk/slash will be ignored by the CF Server
*/
3.   Here's where we get just a little funky. This line is essentially the same as <cfloop from="1" to="#listLen(myList)#" index="i">, otherwise known as a 'for' loop. It's comprised of 3 parts...let's break 'em down to make this easier to decipher:
  • i = 0 -- Straightforward enough. Sets a variable i equal to 0.
  • i LTE listLen(myList) -- Says to continue the loop while i is less than or equal to (LTE) the length of our 'myList' list (which contains 4 elements...so the loop will iterate 4 times).
  • i = i+1 -- Increment i by 1 for each iteration (in other scripting languages, you may have seen this as i++...unfortunately, cfscript does not support this notation).
Notice also, how each 'part' is separated by a semi-colon (;). Notice also the open curly-brace ({) at the end of the line. The code that will execute for each iteration of the loop is enclosed in curly braces (we close our curly brace in line 5).
4.   Here's our output. As we did in our first example, we use cfscript's writeOutput() function. Nested within that function, is a straightforward listGetAt() function...with a <br> concatenated at the end, so we get 4 lines of output after our looping is finished. Again, notice that we end the line with a semi-colon (;).
5.   We're now done with our code inside of the loop, so we close our curly brace.
6.   Close our cfscript block and we're done!


Conditionals in CFSCRIPT

You may also want to look at how CFSCRIPT handles conditionals...otherwise known as <cfif><cfelseif><cfelse></cfif>.

Let's take a very basic example...We're going to generate a random number between 1 and 100...and determined if it's in the first quarter (between 1 and 25), second quarter (between 26 and 50), third quarter (between 51 and 75), or fourth quarter (between 76 and 100).

1.   <cfscript>
2.        myRandomNumber = randRange(1,100);
3.        if (myRandomNumber GTE 1 AND myRandomNumber LTE 25) {
4.             writeOutput(myRandomNumber & ' is in the first quarter');
5.        } else if (myRandomNumber GTE 26 AND myRandomNumber LTE 50) {
6.             writeOutput(myRandomNumber & ' is in the second quarter');
7.        } else if (myRandomNumber GTE 51 AND myRandomNumber LTE 76) {
8.             writeOutput(myRandomNumber & ' is in the third quarter');
9.        } else {
10.             writeOutput(myRandomNumber & ' is in the fourth quarter');
11.        }
12.   </cfscript>


...and the obligatory breakdown :)
1.   Opening our <cfscript> block
2.   Using ColdFusion's randRange() function, we generate a random number between 1 and 100...assinging that value to the variable myRandomNumber.
3.   Our first condition. Checks to see if the value of myRandomNumber is between 1 and 25 (inclusive). This uses standard ColdFusion comparsion operators GTE and LTE for 'greater-than-or-equal-to' and 'less-than-or-equal-to'. We end the line with a curly brace...as with our loop example above, any code within the curly braces will appear if this condition is met (curly braces are not mandatory if there is only one line of code to execute in the condition...however, I include them here to show syntactically correct structure).
4.   This is code that will execute if the condition in line 3 (above) is met. A simple writeOutput() (which you're familiar with by now) showing the actual value of the variable myRandomNumber, and concatenated with a string literal to show that the number is in quarter one.
5.   If the previous condition is not met, we specify another condition (checking for the second quarter, or values between 26 and 50 (inclusive)). The logic is the same as in the first condition. The difference to note is the else if. This is different than ColdFusion's tag-based <cfelse>, which is one word.
6.   The code to execute if the condition in line 5 (above) is met. Same as line 4.
7.   See line 5 :)
8.   See line 6 :)
9.   Our final condition. We can use a simple else as opposed to the else if. If none of the previous 3 conditions are met, this is the only one left...as such, we do not have to specify 'if myRandomNumber GTE 76 AND myRandomNumber LTE 100', as it is implicit.
10.   See line 6 :)
11.   Close our one open curly brace.
12.   Close our cfscript block and we're done!


That's about all for this lesson. There's much more that you can do with CFSCRIPT that I did not cover here. In addition to FOR loops, you can do CONDITIONAL loops and DO WHILE loops. For conditional processing, you can also use SWITCH/CASE statements instead of (or in addition to) the conditional example above.

For those of you who don't have experience with scripting language syntax, it will certainly be awkward at first. However, I urge you to give it a try. If you have any questions about the samples above, or would like to see other examples of CFSCRIPT, leave a message in the easycfm.com forums :)
All ColdFusion Tutorials By Author: Charlie Griefer (CJ)
  • CFSCRIPT Intro
    An introductory look at CFSCRIPT. Rules, some basic syntax, and a couple of examples of loops and conditional processing.
    Author: Charlie Griefer (CJ)
    Views: 46,874
    Posted Date: Saturday, January 18, 2003
  • ColdFusion Mad Libs - Part I
    A silly but fun time-waster that you can easily include on your Web site. You might be surprised at how addicting it can become :)
    Author: Charlie Griefer (CJ)
    Views: 27,666
    Posted Date: Thursday, May 29, 2003
  • ColdFusion Mad Libs - Part II
    You've finished the first Mad Libs tutorial, but you feel like there's something missing. Of course there is! You want to be able to save the final output to a database to let your visitors browse through other user's stories. Includes a bad-words filter for the more conservative among us :)
    Author: Charlie Griefer (CJ)
    Views: 22,839
    Posted Date: Thursday, May 29, 2003
  • to cfqueryparam or not to cfqueryparam
    It's been out there since ColdFusion 4.5...most of us have heard of it...few of us use it. Here are some compelling reasons why you should get into the habit of using the tag.
    Author: Charlie Griefer (CJ)
    Views: 34,135
    Posted Date: Thursday, May 29, 2003
  • Dynamic Column Output (Part One)
    Have you ever wanted to display your content in rows of 3 columns? If you ever wanted to specify the number of columns per row within your content, here's the tutorial for you.
    Author: Charlie Griefer (CJ)
    Views: 34,987
    Posted Date: Thursday, May 29, 2003
  • Dynamic Column Output (Part Two)
    This tutorial picks up where the Dynamic Columns tutorial left off, showing you how to not only output your data in a specified number of columns, but how to do it while still publishing well formed HTML.
    Author: Charlie Griefer (CJ)
    Views: 27,534
    Posted Date: Saturday, May 31, 2003
  • Remote File Management
    Manage text-based files on your server from any Web browser. Create a new file, edit a file, or delete a file. Can be a life saver if you're on the road, and find an error in some of your code that needs a quick fix.
    Author: Charlie Griefer (CJ)
    Views: 27,815
    Posted Date: Tuesday, June 3, 2003
  • Save your visitor's clickstreams
    A nifty little custom tag that will allow you to save a visitor's clickstream through your site, as well as display it back to them (with links). Did I really just say 'nifty'?
    Author: Charlie Griefer (CJ)
    Views: 25,608
    Posted Date: Monday, June 16, 2003
  • Grouping Output in CF
    How to group cfquery output in order to effectively display relational database data. Includes an overview of how to output nested groups as well.
    Author: Charlie Griefer (CJ)
    Views: 32,508
    Posted Date: Tuesday, June 17, 2003
  • arrays and structures - part 1
    part one of a three-part tutorial designed to gently introduce you to the world of complex variables.
    Author: Charlie Griefer (CJ)
    Views: 38,749
    Posted Date: Monday, August 11, 2003
  • arrays and structures - part 2
    part two of a three-part tutorial designed to gently introduce you to the world of complex variables.
    Author: Charlie Griefer (CJ)
    Views: 28,290
    Posted Date: Monday, August 11, 2003
  • arrays and structures - part 3
    part three of a three-part tutorial designed to gently introduce you to the world of complex variables.
    Author: Charlie Griefer (CJ)
    Views: 33,333
    Posted Date: Monday, August 11, 2003
  • JavaScript Form Validation
    Yes, I know we're a ColdFusion site...but ColdFusion does not live in a vacuum. We have to know SQL, HTML, CSS...and sometimes...JavaScript! This tutorial focuses on using JavaScript (in lieu of cfform) to create client side form validation (and explains why writing your own is better than using ).
    Author: Charlie Griefer (CJ)
    Views: 58,285
    Posted Date: Thursday, August 14, 2003
  • CF 'Best Practices'
    Some tips and techniques that I've picked up over the years. I don't maintain that these are 'official' or 'absolute'...they are simply my preference and things that have worked for me. I would like to share them here, and leave you to make the decision as to whether or not they fit in your 'code arsenal' :)
    Author: Charlie Griefer (CJ)
    Views: 35,638
    Posted Date: Friday, August 15, 2003
  • Helping users obtain their passwords
    Your site requires your visitors to log in. of course, some of your visitors are going to forget their passwords (ok, most will forget their passwords). You don't want them to have to send you an e-mail, and then wait for a response. They need immediate access.

    This tutorial shows two methods by which you can accomodate them.
    Author: Charlie Griefer (CJ)
    Views: 26,199
    Posted Date: Thursday, August 28, 2003
Download the EasyCFM.COM Browser Toolbar!