Variables

Strictly speaking, variables are not data. They are, however, so completely intertwined with data manipulation that it is nearly impossible to speak of one and not the other. A variable is a named object that refers to or contains data; in fact, you can think of a variable as a container. For example, the following line assigns the value 2 to a variable named myVar.

 myVar=2 

You can also set one variable equal to the value of another variable. In the following example, the variable num1 is assigned the value 50. Another variable, named num2, is then assigned the value of the variable num1.

 num1=50 num2=num1 

The value of the second variable, num2, is now 50.

Because JScript is a case-sensitive language, you must be careful how you refer to variables; num1, Num1, and NUM1, for example, would name three different variables. If we had set num2=Num1 in the preceding example, an error would have resulted because our variable was named num1, not Num1.

Variables are so named because the values they contain can change. In the following lines of code, the value assigned to the variable myVar changes three times.

 myVar=10 myVar=someOtherVar myVar=75 

After these three operations, the final value myVar is 75.

Declaring Variables

Many programming languages require the programmer to create, or declare, variables before using them. These languages generate an error if you try to use an undeclared variable. In JScript, however, it is usually unnecessary to explicitly declare variables, although it is considered good practice. To declare a variable, you use the var keyword. The following example declares two variables, myVar and anotherVar, and assigns an initial value of 50 to anotherVar (a process referred to as initializing the variable).

 var myVar var anotherVar=50 

The only time that you must declare a variable in JScript is when you want to create a variable that has only local scope. A variable with local scope is available only inside the function in which it is declared. Using variables with local scope, when possible, helps to reduce memory consumption and can result in performance improvements. Explicitly declaring variables also can make your code easier to debug. If you do not explicitly declare a variable, or if you declare it outside a function, it is said to have global scope, which means that it can be written to or accessed by code anywhere in the program.



Dynamic HTML in Action
Dynamic HTML in Action
ISBN: 0735605637
EAN: 2147483647
Year: 1999
Pages: 128

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net