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

It's All About Context

Now we are getting to the heart of the matter: what is the difference between using var, and not using var, to declare a variable? The answer, "execution context." Execution context is the difference between local and global variables.

"What is execution context?"

I'm glad you asked.

Execution Context

A JavaScript program, like many programming languages, has different levels, nested layers, or whatever you want to call them. In HTML, there are various document levels, some nested inside others, for example, a table cell element is nested inside many levels: <html> » <body> » <table> » <tr> » <td>.

An execution context is a similar concept involving something called "scope.". I am not going to get too far into execution contexts and variable scope in this article. A quick example will do.

In this example I define two variables, both named x. The are, however, not the same x, because they are defined in two different execution contexts. The first x is defined in the global scope. And the second x is defined in the local scope of the function SetX. Because each x variable is defined in a separate execution context (global vs. local to function SetX), they have different scopes and will remain independent of each other.



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