The JavaScript Diaries: Part 2 - Page 2 | WebReference

The JavaScript Diaries: Part 2 - Page 2

The JavaScript Diaries: Part 2


Variables are a basic technique used for storing data in a script. A variable "holds" a specific value. In HTML coding, elements such as <em></em> and <h2></h2> are also known as "containers." The code affects the data which is "contained" within the elements. So it is with a variable. Anything done to a variable affects the value that is contained within it. Variables make data manipulation easier as the value can be acted upon without having to re-enter the original data each time.

When a variable is first stated in the code, it is said to be "declared," using the var reserved word. When data is given to the variable to be stored, it is "initialized." If the data is later changed, the new value is "assigned."

A variable can be declared and initialized using one of two methods. With the first method, you would declare the variable on one line and then initialize it on another line:

  var myName;

Basically these two lines say that I am declaring a variable named myName and the variable named myName contains the value "Lee."

Using the second method, you would declare the variable and initialize it all on the same line:

  var myName="Lee";

This line says I am declaring a variable named myName and its value is "Lee." It's the same as above only shorter. The benefit becomes more apparent when you are using several variables.

Naming Variables

Variable are case sensitive. myValue and MyValue are two different variables according to JavaScript. The same case must be used throughout the entire script.

There is no real "correct" way to name variables, but there is an "unofficial" method. When naming a variable that is only one word, use lowercase: var auto. If a variable is two or more words, capitalize the first letter of each word, var MyAuto or capitalize all the words except the first: var myFavoriteCar. The method of capitalization is a personal choice but must be consistent!

A variable can only begin with either a letter or underscore character ( _ ). The rest of the variable name may contain letters and numbers, the underscore character ( _ ), and a dollar sign ( $ ). Do not use a reserved word for a variable name.

Be sure and give meaningful names to variables. Later, when you begin writing complex scripts and you have several variables, a meaningful name helps you to remember what the variable is used for. For instance, if you are adding together the cost of accessories for a car, the statement:


doesn't mean too much just looking at it, but if you use meaningful names for your variables, the statement would then make more sense:


Since JavaScript, for the most part, ignores whitespace, you can write the variables either way:

  var TheFirst="This string is stored in a variable.";
  var TheFirst = "This string is stored in a variable.";

Created: April 29, 2005