DHTMLdev.com — Dedicated to quality Web development articles and tutorials
To var or Not to var PDF Print E-mail
Sunday, 19 March 2006
Article Index
To var or Not to var
What Does var Do?
It Is All About Context
How var Affects Variable Scope
Why You Should Always Use var
Conclusion

What Does var Do?

To start clearing up this confusion, let's look at the seminal JavaScript 1.1 specification published by Netscape in 1996.

JavaScript variables may be declared by assignment or by use of the var statement. For example, both of the following statements declare the variable x:

x = 42
var x = 42

A variable declared outside a function is a global variable, and is accessible everywhere in the global scope. A variable declared by assignment inside a function is also a global variable. A variable declared with var inside a function is a local variable, and is accessible only within that function.

JavaScript Specification

The above quotation should clear up a lot of the confusion. If not, allow me to explain. The specification states that there are two ways to declare a variable: first, by assignment, and second, by use of the var statement. Let's look at the first method, by assignment.

Declaring a Variable By Assignment

The first method of creating a JavaScript variable is "by assignment.&qout;, in other words, by using the = operator. If you write x = 10, you have just assigned a value of 10 to a variable named x. If the variable did not previously exist, then it would be created by default.

The most notable aspect of declaring a variable by assignment is that you create a global variable.

Declaring a variable by assignment has it's use, however, is not a good coding practice. Yet JavaScript allows it, and this is exactly what causes confusion and coding bugs. I will explain why in a moment. But, first, let's look at the second way to declare JavaScript variables.

Declaring a Variable Using the var Statement

The second method of declariing a JavaScript variable is by using a var statement. This creates a local variable. If you write var x = 10, you have actually done two things, similar to before, except that you have declared a local variable.



Last Updated ( Sunday, 19 March 2006 )
 
< Prev   Next >