O'Reilly logo

Professional ASP.NET 3.5 AJAX by Matt Gibbs, Dan Wahlin, Bill Evjen, Dave Reed

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.4. Scoping Variables

Not only can variables in JavaScript be used to refer to any type of object at any time, they can actually be used without being declared at all. This can be a source of problems that are hard to identify because it will not be considered an error if you mistype a variable name. Rather, JavaScript will just assume that you are introducing a new variable.

A variable's scope is the context of code where that variable can be accessed. Whenever a variable is defined, it is assigned a scope for access based on where it is in the code. It is available to all inner scopes; loops, function calls, and further nested control structures. Basically, it is available from the point it is first defined until the scope in which it was defined exits.

A variable is never available at a higher scope. If you declare a variable for use within function MyFunction(), for example, that variable and its value are not available to the caller but are available to any functions that MyFunction() calls. In fact, the variable is available to any functions called by functions that MyFunction() calls. This means there is no concept of local variables that are not visible outside your function (only those you call, and the functions they call, can see them).

JavaScript allows you to use a variable without declaring it (where it will be implicitly declared), but it changes the scope for that variable from what you would typically expect. An undeclared variable is automatically assigned a ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required