home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


JavaScript: The Definitive Guide

Previous Chapter 5
Statements
Next
 

5.10 var

We saw the var statement in Chapter 3, Variables and Data Types; it provides a way to explicitly declare a variable or variables. The syntax of this statement is:

var name_1 [ = value_1] [ ..., name_n [= value_n]]

That is: the var keyword is followed by a variable name and an optional initial value, or it is followed by a comma-separated list of variable names, each of which can have an initial value specified. The initial values are specified with the = operator and an arbitrary expression. For example:

var i;
var j = 0;
var x = 2.34, y = 4.12, r, theta;

If no initial value is specified for a variable with the var statement, then the variable will be defined, but its initial value will be the special JavaScript undefined value.

The var statement should always be used when declaring local variables within functions. Otherwise, you run the risk of overwriting a top-level variable of the same name. For top-level variables, the var statement is not required. Nevertheless, it is a good programming practice to use the var statement whenever you create a new variable. It is also a good practice to group your variable declarations together at the top of the program or at the top of a function.

Note that the var statement can also legally appear as part of the for and for/in loops, in order to declare the loop variable as part of the loop itself. For example:

for(var i = 0; i < 10; i++) document.write(i, "<BR>");
for(var i = 0, j=10; i < 10; i++,j--) document.write(i*j, "<BR>");
for(var i in o) document.write(i, "<BR>");
A variable declared in a loop in this way is not local to the loop as it would be in C++ or Java; its scope is the same as it would be if it had been declared outside of the loop.


Previous Home Next
with Book Index function

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell