Automatically Global

Back

To help with clarity, an example of nested scopes is on the left:

Here, the code inside the inner function has access to all three variables. The code inside outer can only access g and x, and the code outside of the outer function can only see g.

Put in terms of scope, g is global, x is local to outer (or, equivalently, the scope of x is the outer function), and y is local to inner (i.e. its scope is inner).




If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare carName as a global variable, even if it is executed inside a function.

// code here can use carName
function myFunction() {
    carName = "Volvo";
    // code here can use carName
}

HTML file: Displayed by browser:
<body>
<p>If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable:</p>
<p id="demo">First Display Here</p>
<p id="demo1">Second Display Here</p>
<script>
  myFunction();
   document.getElementById("demo").innerHTML =
   "I can display " + carName + " (1st Highlight)";

   function myFunction() {
   carName = "Volvo";
   document.getElementById("demo1").innerHTML =
   "I can display " + carName+ " (2nd Highlight)";

  }
</script>
</body>

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable:

First Display Here

Second Display Here

I'm having a LOT of trouble following this. I googled global variables, and understand that global variables can be difficult in big HTML documents and really are best avoided. I'll take that as good advice because I really don't understand this at all!

BackTable of ContentsNext