1. Computing

JavaScript By Example

16. Scope


The code for this exmple is exactly the same as we had in the last example showing how to write functions in JavaScript. We are however going to look at a different section of the code. What we are concerned with here is the scope of the JavaScript variables. A variable is in scope between when it is created and when it ceases to exist and where variables are defined determine their scope.

In this example code the col variable is defined outside of any function and therefore has global scope. It exists from when the JavaScript starts running until the web page is unloaded. The favcol variable has local scope because it is defined inside the displayMessage function. That means that favcol is created whenever displayMessage is called and it ceases to exist when displayMessage finishes running.

Not demonstrated in this example is what happens if you use the same name for a local variable as you do for a global variable. What happens when you do that is that the global variable will become temporarily inaccessible while a local variable of the same name is in scope and it will become accessible again (still holding the same value) when the local variable is no longer in scope).


<title>Example 16</title>
<p id="ex"></p>
<script type="text/javascript" src="example16.js"></script>


var col;
getColour = function() {
return window.location.search.substring(1);
displayMessage = function(colour) {
var favcol;
favcol = ('green' === colour) ? 'is green.' : 'is not green.';
document.getElementById('ex').innerHTML = colour + favcol;
col = getColour();

  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. JavaScript By Example - Scope

©2014 About.com. All rights reserved.