MREDKJ.com
JavaScript tutorial: Variable scope and the var keyword.Global means a variable can be referenced anywhere in the current document. Local means a variable can only be referenced within the function it is declared. This page has JavaScript scope examples. For an explanation of the rules, refer to reference_js_intro.html#scope. |
<html> <head> <script type="text/javascript" language="JavaScript"> <!-- var numberCars = 3; // global numberTrees = 15; // global if (numberTrees > numberCars) { var numberRoads = 4; // global } else { var numberLakes = 9; // global, but will be undefined since never get in here. } function simpleFunction() { var colorCar = 'blue'; // local colorTree = 'green'; // global, once this function is called if (colorCar != colorTree) { var colorRoad = 'grey'; // local anywhere in this function after this line } else { var colorLake = 'aqua'; // local, but will be undefined since never get in here. } } //--> </script> </head> <body></body> </html>
Note that this JavaScript is placed between the <body> tags, not in the <head>.
<script type="text/javascript" language="JavaScript"> <!-- var globalVar1 = '(G1) global variable declared with var keyword'; globalVar2 = '(G2) global variable without var keyword'; var someBoolean = true; if (someBoolean) { var globalVar3 = '(G3) global variable declared with var keyword inside if statement'; } function sampleFunction() { var localVar1 = '(L1) local variable declared with var keyword'; localVar2 = '(L2) local variable declared without var keyword'; if (someBoolean) { var localVar3 = '(L3) local variable declared with var keyword inside if statement'; } document.writeln('<b>You can reference all local variables inside the same function the variables are declared.</b><br />'); document.writeln(localVar1 + '<br />'); document.writeln(localVar2 + '<br />'); document.writeln(localVar3 + '<br /><br />'); document.writeln('<b>You can reference all global variables inside any function.</b><br />'); document.writeln(globalVar1 + '<br />'); document.writeln(globalVar2 + '<br />'); document.writeln(globalVar3 + '<br /><br />'); } sampleFunction(); document.writeln('<b>Outside a function, you can only reference local variables that are not declared with the var keyword.</b><br />'); document.writeln('Commented out. Cannot reference (L1)<br />'); //document.writeln(localVar1 + '<br />'); document.writeln(localVar2 + '<br />'); document.writeln('Commented out. Cannot reference (L3)<br /><br />'); //document.writeln(localVar3 + '<br />'); document.writeln('<b>Outside a function, you can reference all global variables.</b><br />'); document.writeln(globalVar1 + '<br />'); document.writeln(globalVar2 + '<br />'); document.writeln(globalVar3); //--> </script>