Main Page

variables in ECMAScript

The previous code defines the variable
test
to have a value of
“hi”
and the variable
test2
to have a
value of
“hola”
. Variables using the same
var
statement don’t have to be of the same type, however, as
shown in the following:
var test = “hi”, age = 25;
This example defines
test
(yet again) in addition to another variable named
age
that is set to the value
of
25
. Even though
test
and
age
are two different data types, this is perfectly legal in ECMAScript.
Unlike Java, variables in ECMAScript do not require initialization (they are actually initialized behind
the scenes, which I discuss later). Therefore, this line of code is valid:
var test;
Also unlike Java, variables can hold different types of values at different times; this is the advantage of
loosely typed variables. A variable can be initialized with a string value, for instance, and later on be set
to a number value, like this:
var test = “hi”;
alert(test); //outputs “hi”
//do something else here
test = 55;
alert(test); //outputs “55”
This code outputs both the string and the number values without incident (or error). As mentioned pre-
viously, it is best coding practice for a variable to always contain a value of the same type throughout
its use.
In terms of variables names, a name must follow two simple rules:
?
The first character must be a letter, an underscore (
_
), or a dollar sign (
$
).
?
All remaining characters may be underscores, dollar signs, or any alphanumeric characters.
All the following variable names are legal:
var test;
var $test;
var $1;
var _$te$t2;
Of course, just because variable names are syntactically correct doesn’t mean you should use them.
Variables should adhere to one of the well-known naming conventions:
?
Camel Notation — the first letter is lowercase and each appended word begins with an upper-
case letter. For example:
var
m
y
T
est
V
alue = 0,
m
y
S
econd
T
est
V
alue = “hi”;
13
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 13


JavaScript EditorFree JavaScript Editor     Ajax Editor


©