Home JavaScript Centrality CSS Studio Tools Projects Links
Language Reference Code Examples

JavaScript Variable Reference

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.

Variable Declaration

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

Variable names in JavaScript can begin with either an underscore "_" or a letter (not a number). The remainder of the JavaScript variable name can contain letters, numbers, the underscore "_" and the "$" sign. Examples of valid variable names are:

var _theVariable = "anteater"

var nTheNumber = 21

var _sendMe$ = "Good Idea"

Remember that JavaScript variables are case sensitive.

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.

Data Types

Variables can contain data of several different types. These data types include:

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.

<script type="text/javascript">
var cGlobal = 'I am a global var'

function myFunc(){
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.