Global variables are ones defined outside of any functions (or
within functions, but defined without the var
keyword). They can be defined in the
following ways:
a = 123 // Global scope var b = 456 // Global scope if (a == 123) var c = 789 // Global scope
Regardless of whether you are using the var
keyword, as long as a variable is defined
outside of a function, it is global in scope. This means that every part
of a script can have access to it.
Parameters passed to a function automatically have local scope. That is, they can be referenced only from within that function. However, there is one exception. Arrays are passed to a function by reference, so if you modify any elements in an array parameter, the elements of the original array will be modified.
To define a local variable that has scope only within the current
function and has not been passed as a parameter, use the var
keyword. Example 13-6 shows a function
that creates one variable with global scope and two with local
scope.
<script> function test() { a = 123 // Global scope var b = 456 // Local scope if (a == 123) var c = 789 // Local scope } </script>
To test whether scope setting has worked in PHP, we can use the
isset
function. But in JavaScript
there is no such function, so Example 13-7 makes use of the
typeof
operator, which returns the
string “undefined” when a variable is not defined.
<script> test() if (typeof a != 'undefined') document.write('a = "' + a + '"<br />') if (typeof b != 'undefined') document.write('b = "' + b + '"<br />') if (typeof c != 'undefined') document.write('c = "' + c + '"<br />') function test() { a = 123 var b = 456 if (a == 123) var c = 789 } </script>
The output from this script is the following single line:
a = "123"
This shows that only the variable a
was given global scope, which is exactly
what we would expect, given that we gave the variables b
and c
local scope by prefacing them with the var
keyword.
If your browser issues a warning about b
being undefined, the warning is correct but
can be ignored.