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


JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

6.13. var

The var statement allows you to explicitly declare a variable or variables. The syntax of this statement is:

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

The var keyword is followed by a comma-separated list of variables to declare; each variable in the list may optionally have an initializer expression that specifies its initial value. For example:

var i;
var j = 0;
var p, q;
var greeting = "hello" + name;
var x = 2.34, y = Math.cos(0.75), r, theta;

The var statement defines each named variable by creating a property with that name either in the call object of the enclosing function or, if the declaration does not appear within a function body, in the global object. The property or properties created by a var statement cannot be deleted with the delete operator. Note that enclosing a var statement in a with statement (see Section 6.18) does not change its behavior.

If no initial value is specified for a variable with the var statement, the variable is defined but its initial value is undefined.

Note that the var statement can also appear as part of the for and for/in loops. 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>"); 

Chapter 4 contains much more information on JavaScript variables and variable declarations.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.