Variables are constructs used to store data in a script--you can think of a variable as a container into which you place your data. Variables can contain data of several different types. The scope of a given variable is dependent upon where in the script the variable is declared. A value can be assigned to a variable upon declaration or after.
A variable is declared by assigning it an intial value. This is typically done using the 'var' assigned word, followed by the variable name, followed by the assignment operator '=', followed by the intial value of the variable. For example:
var cMyString="Hello World!"
declares the variable cMyString and assigns it an initial value of "Hello World!".
Valid Variable Names
var _theVariable = "anteater"
var nTheNumber = 21
var _sendMe$ = "Good Idea"
There is no requirement to name variables based upon the data type contained within, but it is frequently useful to do so. For example, you could start string variables with a 'c' (i.e. cMyString) and numeric variables with an 'n' (i.e. nMyNumber). Such conventions are left to the discretion of the developer. In practice, it often makes sense to use long variable names during development and then to switch to short names when the script is in production to decrease page size.
Variables can contain data of several different types. These data types include:
- string data example: cValue = "hello"
- numeric data example: nValue = 1235
- logical/boolean data example: var lValue = true
- array data example: aValue = new Array(5)
- date/time data example: dValue = new Date()
- null data - no data, different from an empty string or a zero numeric variable example: var nuValue=null
For a more in-depth discussion of data types, go to the Data Types Page.
Scope refers to the area in which a given variable is available. For example, a variable declared within a function is available within that function and is destroyed at the end of that function. Such a variable is referred to as a local variable. A Variable that is declared outside of a function is referred to as a global variable. Global variables are available anywhere on the page and are also available to any functions called after the global variable declaration. Global variables are available until the page is closed/destroyed.
In the following example, the local variable cLocal is only available inside the function named myFunc(). The global variable cGlobal, on the other hand, is available everywhere on the page once declared.
var cGlobal = 'I am a global var'
var cLocal = 'I am a local var'
Because global variables are available everywhere on the page, one should make sure that there are no local variables with the same names as global variables.