Variables declared outside a function with or without var are global
Variables declared inside a function without var are global
Variables declared inside a function with var are local to that function
A global and a local variable can have the same name, although not advisable.
The global variable cannot be used in the same function as the local variable with the same name.
Click a function name to see example
| var count=0 | Count is set both as a global variable |
| function one(){ var count=1 |
and a local variable in function one. The local count value will always be as defined in function one irrespective of the value of the global count |
|
function two(){ |
Function two will always show the current value of the global count. |
|
function three(){ |
Function three will change the value of the global count each time it is run. |
|
ONE
|
|
|
<script type="text/javascript"> |
<a href="#" onclick="test(1)">ONE</a> |
The above script does not serve any purpose other than to show the principles behind its function.
Script Breakdown
<a href="#" onclick="test(1)">ONE</a>
<a href="#" onclick="test(2)">TWO</a>
<a href="#" onclick="test(3)">THREE</a>
<a href="#" onclick="test(4)">FOUR</a>
When the script first loads variable a, being outside the function, is set to zero.
Argument n is given a value when the function is called by the onclick event
Variable a is then given the same value as argument n at the end of the function after the functions action.
This means that the value of a can be used in the functions action to determine a previous value of n.
Note:
If you look at the script in the source of this document you might get a bit confused as I have incorporated other functions and actions in order to get the display effects for the examples above.