Introduction
Overview
History
Advice
Books
Tutorials
Source Code
Top 100
Reference

Beginners
Sample Code
IDE
Syntax
Variables
Boolean Logic
Strings
Arrays
Conditional Flow

Intermediate
Date-Time
Math
Functions
Event Handlers
Error Handling

Advanced
Objects
Dynamic HTML
Cookies
Multimedia
CGI
Java Applets
Distribution

Community
Web Sites
Mailing Lists
USENET
Vendors
News

GBIC >> JavaScript >> Variables
Like all languages, JavaScript supports variables, which are simply names which can be assigned values. A variable name must follow certain rules:

  • are case-sensitive. x and X are different variables
  • must start with a letter, underscore, or dollar sign
  • can be of any length
  • have no limit on length
  • cannot use reserved words
Data Types
JavaScript uses only four data types. Variables can contain any of the data types and the data type of the variable can be re-assigned at any time. Supported data types are:
  • string
    Example: "abc" or "123"

  • number
    Example: 56 or 1.35

  • boolean
    Example: true or false (only two boolean values are allowed)

  • object
    (see example in Object tutorial)

The data type contained within a variable can be checked using the 'typeof' function provided by JavaScript, as in this example:

if (typeof myvariable="number") ...

Special Values
JavaScript also supports two special values which can be assigned to variables:

  • Undefined - variable has been created but no value assigned
  • Unll
Creating Variables
Variables can be created in two ways, by declaration or by assignment.

Although JavaScript variable do not have to be declared before using them, it is considered good practive to do so.

To create a variable by assignment, use this code:

newVariable = 5		//create a variable simply by assigning it
newVariable = "dog"	//variables can be any type
newVariable = 'dog'	//single or double quotes can be used on strings

To create one or more variables by declaration, use the 'var' keyword, as in this example:

var X
var X, Y	//note the comma between the two variables

A variable can be assigned a value at the same time as it is created, as in this example:

var X = 6
var X=6,Y=7    //note the comma between the two declarations

Use of the 'var' operator affects the scope of the variable. Scope defines where a variable may be accessed within a JavaScript program. When 'var' is used to declare a variable, the variable may not be accessed within any function or other JavaScript program. It may only be accessed within the body of the JavaScript program where it was created.

Likewise, declaring a variable using 'var' within a function denies access to any JavaScript code outside that function.

See the Function tutorial for more information on Scope.