Variable (Definition)

A named storage receptacle for script accessible values.

Availability:

ECMAScript edition - 2

Variables are containers with names that you can manage from your JavaScript code. You can create new ones when you need to, and change the values that are stored in them whenever you want.

Some variables are available only within the function block that is currently executing while others are available all the time. The first kind are called local variables and the second are called global variables.

The availability of a variable is determined by the scope chain rules that are in force at any particular time.

When a primitive value is stored in the variable, a unique copy of that value is associated with the variable. However, when an object is stored in a variable, the variable contains only a reference to the object. The object's reference count is incremented and is only decremented when a reference to it is discarded. To discard the reference to an object that is contained in a variable, it must be deleted explicitly. This will not affect the object but will reduce its reference count by one. When its reference count is zero, the object can be purged from memory. Whether that happens or not depends on the way that garbage collection is managed. It is possible that simply replacing an object reference with some other value may not properly decrease the reference count in some implementations. This can lead to a memory leak.

Example code:

   // Simple variable declaration.
   var myVariable;
   // Declare and initialize a variable to a null value.
   var emptyVar = null;
   // Declare and initialize to a floating point value.
   var priceData = 11.50;
   // Assign a string value to a variable.
   someString = "23 The Irons, Cleethorpes";
   // Assign a boolean value to a variable.
   aBooleanValue = true;
   // Assign an exponential value to a variable.
   scientificValue = 1.34e+17;
   // Assign a hex value to a variable.
   aHexValue = 0xFF34;
   // Assign an octal value to a variable.
   AnOctalValue = 0177;
   // Use an unusual variable identifier name.
   $_funnyVarName = "Be careful with var names";
   // Declare and initialize several variables on one line.
   var aaa = 1, bbb = 2, ccc = 3;
   // Store an object reference in a variable.
   myObject = new Object();

See also:Constant, Function arguments, Garbage collection, Memory leak, Reference counting, Scope, Scope chain

Cross-references:

ECMA 262 edition 2 - section - 7.5

ECMA 262 edition 2 - section - 10.1.3

ECMA 262 edition 2 - section - 12.2

ECMA 262 edition 3 - section - 7.6

ECMA 262 edition 3 - section - 10.1.3

ECMA 262 edition 3 - section - 12.2

O'Reilly JavaScript Definitive Guide - page - 52

Wrox Instant JavaScript - page - 13