Skip to Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

Variable Declaration

Before you use a variable in a JavaScript program, you must declare it.[12] Variables are declared with the var keyword, like this:

var i;
var sum;

You can also declare multiple variables with the same var keyword:

var i, sum;

And you can combine variable declaration with variable initialization:

var message = "hello";
var i = 0, j = 0, k = 0;

If you don’t specify an initial value for a variable with the var statement, the variable is declared, but its initial value is undefined until your code stores a value into it.

Note that the var statement can also appear as part of the for and for/in loops (introduced in Chapter 6), allowing you to succinctly declare the loop variable as part of the loop syntax 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>");

Variables declared with var are permanent: attempting to delete them with the delete operator causes an error. (The delete operator is introduced in Chapter 5.)

Repeated and Omitted Declarations

It is legal and harmless to declare a variable more than once with the var statement. If the repeated declaration has an initializer, it acts as if it were simply an assignment statement.

If you attempt to read the value of an undeclared variable, JavaScript will generate an error. If you assign a value to a variable that you have not declared with var, JavaScript will implicitly declare ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata