The region of a program in which a variable is accessible is called scope. Javascript has two kinds of scope: global and local. A variable of global scope is accessible anywhere within a program (that is, any Javascript statement block within an HTML page). Variables of local scope are declared within functions; they are accessible only within the statement body of the respective function.
Within a function, local variables take precedent over global variables. That is, if a program contains two variables with the same name--one of global scope, the other declared within a function--the local one will be used in the function's statement block.
Javascript does not know block-level scoping. If a variable is declared within a for
or while
loop, for example, this variable will be accessible even outside the loop block.
The following scripts appear in the <head> and <body> sections of this page. The <head> section declares a global variable, global_var
, and a function, outer( )
, that contains a local variable, local_1
, and a nested function, inner( )
, with yet another variable of local scope, local_2
.
The <body> script prints the global variable and calls the function outer( )
, which in turn prints the variables within its scope, etc.
The script in the <head> section:
</style> <script type="text/javascript"> // <![CDATA[ var global_var = "Hello #1<br />"; function outer() { var local_1 = "Hello #2<br />"; function inner() { var local_2 = "Hello #3<br />" document.write("From inner(): " + global_var); document.write("From inner(): " + local_1); document.write("From inner(): " + local_2 + "<br />"); } document.write("From outer(): " + global_var); document.write("From outer(): " + local_1 + "<br />"); inner(); // out of scope: will generate a Javascript error document.write("From outer(): " + local_2 + "<br />"); } // ]]> </script>
The script in the <body> section:
<script type="text/javascript"> // <![CDATA[ document.write("From page: " + global_var + "<br />"); outer(); // out of scope: will generate a Javascript error document.write("From page(): " + local_1); // ]]> </script>
Note that the Javascript errors generated by calling variables out of scope do not appear in the HTML output i most browsers. Safari 1.2.4 on Mac OSX 10.3.8, however, executes the statements and prints the variables as 'undefined' values. They can also be seen--in part, at least--in the Javascript console of the Netscape-family browsers.