The JavaScript Diaries: Part 4 - Page 3
[previous] [next]
The JavaScript Diaries: Part 4
Global and Local Variables
As you have seen, variables can be used within functions, but not all variables used within a function are the same. There are two types of variables used within a function: global and local.
Global Variables
These are variables declared outside the function, within the overall script.
If the value of a global variable is reassigned (changed) within a function,
it will be reassigned throughout the entire script. This is because it "belongs"
to the script itself. When a global variable is sent to a function, just the
variable name is used (don't use the reserved word var
). All of
our examples so far in this installment have been local since all used the var
reserved word.
If we create the following script, and declare the variables using the reserved
word var
, it will write "I like the Delta blues" on the page:
<script type="text/javascript"> <!-- var place="Delta"; var type="blues"; document.write("I like the " + place + " " + type); //--> </script>
If we take the same script, add a function and reuse the global variables
above within the function without using the reserved word var
,
it will create a bit of a problem, as shown below. Put this in the <head>
section:
<script type="text/javascript"> <!-- var place="Delta"; var type="blues"; function music() { place="New Orleans"; type="jazz" document.write("I like " + place + " " + type); } //--> </script>
Then, add this in the <body>
section:
<script type="text/javascript"> <!-- music(); document.write(" but I really like " + place + " " + type); //--> </script>
Here is what will happen:
|
Local Variables
These variables are declared within the function (hence, they are "local").
In order to be declared locally they must be declared using the reserved word
var
. You can even use the same name as a global variable but its
value will only be used within the function. If we use our previous example
and add the var
reserved word before the variables within the function,
we will get the anticipated result. Go ahead and try both of them yourself.
<script type="text/javascript"> <!-- var place="Delta"; var type="blues"; function music() { var place="New Orleans"; var type="jazz" document.write("I like " + place + " " + type); } //--> </script>
<script type="text/javascript"> <!-- music(); document.write(" but I really like the " + place + " " + type); //--> </script>
As far as the JavaScript interpreter sees it, the variables place
and type
declared at the very beginning of the script are completely different than the variables place
and type
declared locally within the function. Be sure to remember that, without using the var
reserved word within the function when declaring variables, you will be assigning a new value to an existing global variable.
[previous] [next]
Created: May 27, 2005
URL: