After you start adding conditions, functions, and loops to your JavaScript applications, you need to understand variable scoping. Variable scoping sets out to determine the value of a specific variable name at the line of code currently being executed.
JavaScript enables you to define both a global version and a local version of a variable. The global version is defined in the main JavaScript, and local versions are defined inside functions. When you define a local version in a function, a new variable is created in memory. Within that function, you reference the local version. Outside that function, you reference the global version.
To understand variable scoping a bit better, consider the code in Listing 1.4.
01 var myVar = 1;
02 function writeIt(){
03 var myVar = 2;
04 console.log("Variable = " + myVar);
05 writeMore();
06 }
07 function writeMore(){
08 console.log("Variable = " + myVar);
09 }
10 writeIt();
The global variable myVar
is defined on line 1, and a local version is defined on line 3, within the writeIt()
function. Line 4 writes "Variable = 2"
to the console. Then in line 5, writeMore()
is called. Since there is no local version of myVar
defined in writeMore()
, the value of the global myVar
is written in line 8.