MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Extension

Variables and their Scope

As you might have discovered, if you forget to declare a variable JavaScript will implicitly declare it for you. That is, if you write origBgCol = document.bgColor, JavaScript will declare the variable origBgCol if it has not previously been declared in some way (such as with a var statement). However, if you attempt to retrieve a value from a variable that has not been declared, as in document.bgColor = origBgCol, then JavaScript will report an error.

Also associated with variable declaration is the variable's scope and its search chain. These define respectively the region of the JavaScript program in which the variable can be seen, and the way in which JavaScript looks for the variable, and operate in the same way as they do in Java. Details can be found in JavaScript, The Definitive Guide, 3rd edition, by David Flannagan, O'Reilly Books, 1998. The rules explain why the following solution to Exercise 4 will not work:

    <A HREF = "http://www.most-expensive-sellers.com" 
      onMouseOver="var origBgCol=document.bgColor; 
        document.bgColor = 'coral';return false" 
      onMouseOut="document.bgColor=origBgCol">
    Come to our cheap on-line store
    </A>
      

In the above example, the scope of origBgCol is the onMouseOver event handler, as this is where the variable is declared. Since the onMouseOver and onMouseOut scopes do not overlap, when JavaScript searches for origBgCol in the onMouseOut handler will not find the variable, and since it is attempting to obtain a value from an undeclared variable, an error is reported. Declaring origBgCol in the onMouseOut handler would not work either, as all it would do is declare two separate variables which have the same name in different scopes.

The solution to this is to declare the variable outside of both handlers, in some scope which they can both access.