Global and Local Variables


Global and Local Variables

For most JavaScript developers, there are only two basic scopes: global and local. A global variable is one that is known ( visible ) throughout a document, while a local variable is one limited to the particular block of code it is defined within. The body of a function has its own local scope. For example, in the script here, the variable x is defined globally and is available within the function myFunction, which both prints and sets its value.

 // Define x globally var x = 5; function myFunction() {   document.write("Entering function<<br />>");   document.write("x="+x+"<<br />>");   document.write("Changing x<<br />>");   x = 7;   document.write("x="+x+"<<br />>");    document.write("Leaving function<<br />>"); } document.write("Starting Script<<br />>"); document.write("x="+x+"<<br />>"); myFunction(); document.write("Returning from function<<br />>"); document.write("x="+x+"<<br />>"); document.write("Ending Script<<br />>"); 

The output of this script is shown at right. Notice in this case that the variable x can be both read and modified both inside and outside the function. This is because it is global.

click to expand

Global variables aren t always helpful because they prevent us from reusing functions easily. If a function uses a global variable, you can t just copy it from one script into another and expect it to work. You must also copy the global variable it relies on. This is problematic for many reasons, primarily for the aforementioned reason: it reduces reusability. A proliferation of globals also makes it hard to understand what a script is doing.

Instead of using global variables, we can define local variables that are known only within the scope of the function in which they are defined. For example, in the following script the variable y is defined locally within the function myFunction and set to the value 5.

 function myFunction() {   var y=5;  // define a local variable   document.write("Within function y="+y); } myFunction(); document.write("After function y="+y); 

However, outside the function, y is undefined so the script will throw an error message:

click to expand

To fix the execution of this script, we can replace the second output statement with a small if statement to determine if the variable y is defined within the current context, namely, the current window :

 if (window.y)  document.write("After function y="+y); else  document.write("y is  undefined  "); 

Notice that in this case the script shows that indeed the variable y is undefined in the global space:

click to expand

However, more likely, we purposefully want to create local variables that are not known in the global scope so that we can hide the implementation of the function from the code that uses it. This separation between call and implementation allows for the clean function reuse alluded to earlier, but be careful ”sometimes the use of local and global variables can get confusing, particularly when there are the same names in use.

Mask Out

The use of the same variable names for both local and global variables creates a potentially confusing situation, often termed a mask out . Notice in the example here how both local and global variables named x are used:

 var x = "As a global I am a string"; function maskDemo() {  var x = 5;  document.write("In function maskDemo x="+x+"<<br />>"); } document.write("Before function call x="+x+"<<br />>"); maskDemo(); document.write("After function call x="+x+"<<br />>"); 

As shown in the output here, the value change made in the function is not preserved, because the local variable effectively masks the global one.

click to expand

As a general rule, when both a local and global variable have the same identifier, the local variable takes precedence. However, it s best to just avoid any potential confusion by never giving two variables the same identifier. Occasionally, this won t be feasible , for example, if you re reusing a large number of scripts maintained by different people in the same page. In this case, you could name local variables with the function name prepended, for example, maskDemoX instead of x .

Local Functions

It might also be useful, in addition to limiting a variable s scope to a particular function, to create a function local to a function. This capability is not surprising if you consider that it is possible to create local objects and that functions themselves are objects (as we ll see in the next section, Functions as Objects ). To create a local function, just declare it within the statement block of the function to which it should be local. For example, the following script shows a function called testFunction with two locally defined functions, inner1 and inner2 :

 function testFunction() {  function inner1() {   document.write("testFunction-inner1<<br />>"); }  function inner2() {   document.write("testFunction-inner2<<br />>");   } document.write("Entering testFunction<<br />>"); inner1(); inner2();   document.write("Leaving testFunction<<br />>");  }    document.write("About to call testFunction<<br />>");  testFunction();  document.write("Returned from testFunction<<br />>"); 

From within the function it is possible to call these functions as shown in the preceding , but attempting to call inner1 or inner2 from the global scope results in error messages, as demonstrated here:

 function testFunction() {  function inner1()   {     document.write("testFunction-inner1<<br />>");   }  function inner2()   {     document.write("testFunction-inner2<<br .>>");     }  }  inner1();  // this will error because inner1 is local to testFunction 
click to expand

While using local functions provides us with some ability to create stand-alone modules of code, such techniques are rarely seen in JavaScript. Part of the reason is that local (or nested ) functions have been supported only since the 4. x generation of browsers. The other reason, of course, is that unfortunately most JavaScript programmers do not practice such modular coding styles.




JavaScript 2.0
JavaScript: The Complete Reference, Second Edition
ISBN: 0072253576
EAN: 2147483647
Year: 2004
Pages: 209

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net