This lesson deals with working with data using variables, one of the most important concepts to get to grips with when learning programming.
Variables are places where a programmer can store data in the web servers memory. This data will be kept in memory for the life of the current page and are wiped when the page has finished executing.
You can name variables using letters, numbers or underscores, but the name must begin with a letter or an underscore. Names in VBScript are not case sensitive but in other languages such as JScript they can be.
Take a look at the following statement:
annualSpend = monthSpend * 12
Pretty clear what is going on isn’t it? Anyone who has done some algebra should not have a problem working with variables.
One of the major failings of VBScript and Classic ASP is the fact that variable types are not enforced properly. ASP pretty much has one type of variable called a Variant and it can take the form of text (a ‘string’ such as “hello world” or ‘character’ such as the letter ‘A’), a number or a logical bit/boolean (true/false).
You are not forced to “declare” your variables before using them but this could get you into trouble with complex scripts. To switch the feature on you use
at the top of your script.
You declare variables in VBScript using Dim, eg.
This tells the server to allocate some spare memory for future use. Once your variable is declared you can fill it with data.
As we have already seen you can do mathematical operations on variables and set the value of a variable quite simply just by saying the variable is equal to another value. Strings require quotes around the value.
myNumber = 10
myString = “hello world”
Once a variable contains a value you can output that value. If you want to add one string to another (“concatenate”) you can use an ampersand.
myVariable = “hello” & “world”
Let’s take a look at an example.
If we take a look at the code you will see it’s really simple
As we progress through this tutorial you will see we can also do some pretty powerful things with strings (text variables) and more complex data types such as arrays and collections.