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

Why You Should Always Use var

Manytimes, JavaScript programmers do not use var. They will define their variables like this:

Although the above variable declarations are legal JavaScript code and work just fine, in some cases, I strongly recommend that you do not drop the use of var. Let's look at an extended example to see why.

In the example above, the variable d is declared by assignment instead of using a var statement. Also, it is declared twice, or is it once? Is it declared in the function DoSomething, or is it declared in the fuction DoSomethingElse? We do not know.

Because the variable d in the example is declared by assignment, it will declared by whichever function happens to be called first. That is confusing. Also, are the two functions actually referring to the same variable? Is the variable d the same thing in both functions? Is it supposed to be global and shared between the two functions? Or is it supposed to be relevant only to that function? Sometimes, different functions happen to use the same name for a local variable. But if both functions declare the variable by assignment, they will be global and each function can overwrite the other function's variable. Or maybe the author intended it to work that way? We really do not know.

Here is a clearer way to handle this situation:

Now we can see that since the var statement was used to declare the variables at the top, that the author intended to declare the variables and then override them in the functions. And d was declared at the top as well. Plus, d is declared with a default value of 0. Also, we can see that in the function DoSomethingElse, the variable d is actually a new and different variable. There are two d variables in this code. It is clear and also it is safe, because DoSomethingElse will not overwrite the global variable d. Additionally, it is clear that DoSomething is in fact overriding a variable d previously defined, because it is not using a var statement.



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