Tutorial — Variables

One Type of Variable

JavaScript only has one type of variable: a reference to an Object. Fortunately, JavaScript is 100% “Object-Oriented”; everything is an Object. There are no “primative” types, such as int in JavaScript.

The var keyword creates a reference variable:

// A reference variable, named foo (current value undefined)...
var  foo;

// A reference variable, named bar, set to 42...
var  bar = 42;
// Same thing, only explicitly creating the object...
var  bar = new Number(42);

// A reference variable, named str, set to Hello, Lola!...
var  str = "Hello, Lola!";
// Same thing, only explicitly creating the object...
var  str = new String("Hello, Lola!");

JavaScript itselt does not require declaration of variables–it will create them the first time it sees them used. However, some environments, such as Siebel, require declaration. In general, in programming, declaring variables is Good Practice.

You can use var inside loops:

// ...
for (var ix=0; ix < 10; ix++)
{
    // do something
}

// ...
for (var prop in anObject)
{
    // do something
}