by Abram Adams - Dec 12, 2013
Page 1 of 2
Often in programming we need to store pieces of information so that it can be used elsewhere in our program. For instance, in a game we may need to save the gamer's current score so that as they achieve goals, we can increase the score. To do this we use what are called `variables`. This is not unique to ColdFusion, but it's one of the first things you'll want to get familiar with on your journey with any programming language. This small course will describe how we create variables in ColdFusion; both in CFScript and in CF Tag based syntax.
Let's start off with the old, *"hello world"* application. I know, this is boring, but it will give us a familiar starting point. we'll get into more interesting stuff as we build on these basics. Anytime you start writing an app, it's important to layout the concept of what the app is to accomplish on "paper" (or in digital form). A basic outline will help guide the development, and keep it within scope. So, for this app we want to: * Print the words "Hello World!" on the page Pretty simple... Now let' get to it. Setting a variable in CFML can be done several ways. The first, and easiest way, in CFScript is to just write something like ```myVariable = 'something';```. The value to the left of the ```=``` is the variable's name, In ColdFusion this name can be pretty much any single string of characters, with the following basic rules: * A variable name must begin with a letter, underscore, or Unicode currency symbol. * The initial character can by followed by any number of letters, numbers, underscore characters, and Unicode currency symbols. * A variable name cannot contain spaces. * ColdFusion variables are not case-sensitive. However, consistent capitalization makes the code easier to read. The value to the right of the ```=``` is what the variable will hold. When reading code, think of the ```=``` as the word **'gets'**. So reading the sample above: myVariable **'gets'** the value of **'something'**. To see this in action, run the code sample below:
If you clicked "Run Code" on the previous code box, you probably noticed nothing happened. The fact is however that something ***did*** happen, we just didn't tell it to send any response back to the screen. Try the next sample, which introduces a CFScript function called ```writeOutput()``` which, you may have guessed writes out the result of the code between ```(``` and ```)``` to the screen.
That's better. Now you should see the word "**something**" in the results tab. Play with that a little, see if you can get it to print your name. Then when you're done, move on to the next page to continue.