CD-53Chapter 7 .Programming Fundamentals, Part II Variable scope (Web hosting india)
CD-53Chapter 7 .Programming Fundamentals, Part II Variable scope Speaking of variables, it s time to distinguish between variables that are defined outside and those defined inside of functions. Variables defined outside of functions are called global variables; those defined inside functions are called local variables. A global variable has a slightly different connotation in JavaScript than it has in most other languages. For a JavaScript script, the globe of a global variable is the current document loaded in a browser window or frame. Therefore, when you initialize a variable as a global variable, it means that all script statements in the page (including those inside functions) have direct access to that variable value. Statements can retrieve and modify global variables from anywhere in the page. In programming terminology, this kind of variable is said to have global scope because everything on the page can see it. It is important to remember that the instant a page unloads itself, all global variables defined in that page are erased from memory. If you need a value to persist from one page to another, you must use other techniques to store that value (for example, as a global variable in a framesetting document, as described in Chapter 16; or in a cookie, as described in Chapter 18). While the varkeyword is usually optional for initializing global variables, I strongly recommend you use it for all variable initializations to guard against future changes to the JavaScript language. In contrast to the global variable, a local variable is defined inside a function. You already saw how parameter variables are defined inside functions (without var keyword initializations). But you can also define other variables with the varkeyword (absolutely required for local variables). The scope of a local variable is only within the statements of the function. No other functions or statements outside of functions have access to a local variable. Local scope allows for the reuse of variable names within a document. For most variables, I strongly discourage this practice because it leads to confusion and bugs that are difficult to track down. At the same time, it is convenient to reuse certain kinds of variable names, such as forloop counters. These are safe because they are always reinitialized with a starting value whenever a for loop starts. You cannot, however, nest a for loop inside another without specifying a different loop counting variable. To demonstrate the structure and behavior of global and local variables and show you why you shouldn t reuse most variable names inside a document Listing 7-2 defines two global and two local variables. I intentionally use bad form by initializing a local variable that has the same name as a global variable. Listing 7-2: Global and Local Variable Scope Demonstration