Variables and Data

You can store information inside pieces of JavaScript code. Here are some examples:

var new_value;
var cost = null;
var new_price = 10.95;
address = "23 Short St.";
var result = 'Result unknown';
result = true;
result = 1.08e+23;
result = 0x2Fe3
result = 0377
$name = "Jimmy Zed";
var first = 1, second = 2, last = 10;

There are two ways to store data—inside a variable or directly typed in as a constant. The example illustrates both with variables on the left of the equals sign on each line, and constant values on the right. Data always has a type, so constants each have a type. Variables take on the type of the data they contain, but since variables can contain data of any type, they change types when the data inside them is changed. The variable has no innate type of its own.

Variables are just a piece of space in computer memory referred to by a name that has to follow some basic rules. Normal English words, possibly strung together with underscores ('_') are safest. The first letter must not be a digit. The first time you use a variable name, that variable can spring into existence automatically, but it's best to use the var keyword as a hint to the computer to tell it the variable is new, and to keep yourself organized. After you use var once, never use it again for that variable. Avoid using variable names that might clash with other uses of the name.

Avoid using $ in variable names—neither Internet Explorer 3.02(with JScript 1.0), nor Navigator 2.02 can handle it. Avoid using names that differ only in case like Fred and fred if you expect to use Internet Explorer 3.02 with JScript 1.0—it can't tell the difference.

© 1997 by Wrox Press. All rights reserved.