Variables are a basic technique used for storing data in a script. A variable
"holds" a specific value. In HTML coding, elements such as
<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,"
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
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; myName="Lee";
Basically these two lines say that I am declaring a variable named
myNameand the variable named
myNamecontains the value "Lee."
Using the second method, you would declare the variable and initialize it all on the same line:
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.
Variable are case sensitive.
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:
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
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:
var TheFirst="This string is stored in a variable."; var TheFirst = "This string is stored in a variable.";