Variable Scope for New Programmers
Got something to say?
Share your comments on this topic with other web professionals
In: Columns > Behind the Curtain
Published on October 17, 2005
I routinely see new programmers running into trouble with the concept of variable scope. It’s an extremely important concept, however, and one that must be understood in order to develop a reliable application. If you work in multiple programming languages, it can get even more confusing—each language has its own set of rules about how variable scope is handled.
First of all, what is variable scope? Essentially, variable scope describes when a piece of information is accessible. When a variable is created, the value it stores is only available for a certain part of the code execution. Memory is set aside to store that piece of information and then freed when it is no longer needed.
When all variables are always available, memory is wasted because it is set aside well before or after it’s needed. This also causes a lot of confusion when a programmer needs to recall used variable names. So, we have scope.
Scope Examples
JavaScript and PHP do not require you to declare a variable before use. This can be handy when you just need to get something done but problematic when troubleshooting.
For example, in JavaScript, a variable declared outside of a function is available inside a function:
var name = "Jonathan";
function showme()
{
alert(name); // will display "Jonathan"
}
showme();
A variable declared within a function will not be available outside of a function.
function showme()
{
var name = "Jonathan";
}
showme();
alert(name); // name will be undefined
Confusion can really begin to set in when using the same variable name inside and outside of a function.
var name = "Jonathan";
function showme()
{
var name = "Snook";
alert(name); // will display "Snook"
}
showme();
alert(name); // will display "Jonathan"
Some languages have syntax to prevent these types of errors from occurring. In PHP, for example, to use a global variable inside a function, you must use the global keyword.
$name = "Jonathan";
function showme()
{
global $name; // variable can now be used in function
echo $name; // will display "Jonathan"
}
Global variables are accessible even within multiple include files.
Avoid Global Variables
With small scripts, you’re not going to run into these types of issues often, because it’s relatively easy to keep track of everything that’s going on. Inevitably, applications become larger and more complex, and tracking down the source of a problem becomes more laborious. One of the best ways to sidestep errors is to avoid using global variables.
There are two ways to minimize the use of global variables:
#1 Do not use global variables from within a function
Instead, pass in any required values as parameters to the function.
Using our JavaScript example from before we can do this:
var name = "Jonathan";
function showme(myname)
{
alert(myname); // will display "Jonathan"
}
showme(name);
alert(name); // will display "Jonathan"
#2 Use object-oriented programming (OOP)
This mantra is similar to the first point, but on a larger scale. Instead of a collection of functions that perform related tasks, the functions become methods of an object. (A method is a function that belongs to an object.) Values can then be passed into the object in a variety of useful ways:
- By setting the properties of an object
- By passing values as parameters of a method
- By passing values as parameters of the constructor (the method that gets executed when an object is first instantiated)
Here’s a quick JavaScript OOP example:
function Person(myname)
{
this.name = myname;
}
var me = new Person("Jonathan");
alert(me.name);
Where to Declare
When traveling between two countries, you declare your goods at the border. Apply this analogy and declare variables at the border of the function—that is, right when you get into a function.
function bigFunction()
{
var name, address, telephone, postal code;
/* pretend there's a long script here */
}
Declaring your variables right away ensures that you haven’t accidentally embedded a variable declaration, like in a while
loop, too deep in the code. It also helps ensure that you’re not reusing variable names that could erase data you’re expecting further on in the function.
Scope in a Recursive Function
A recursive function is one that calls itself, often over and over again. These are sometimes used to build tree views when data is hierarchical. When calling the same function over and over again, we’re reusing the same variable names. What happens to our variables? Take a look at this PHP example:
function overAndOver($limit)
{
$currentvalue++; // current value is now 1
if($limit) overAndOver(--$limit);
$currentvalue++; //current value is now 2
echo $currentvalue . "<br>";
}
overAndOver(20);
Ignore the fact that this loop is somewhat pointless—the basic concept is that $currentvalue
never becomes greater than 2. Think of each execution of a function as a self-contained entity in memory. Even when called from within itself, that new call makes a copy of itself and any variable declarations made within that function stay within it.
Use Scope
Understanding scope will save you time troubleshooting and will make your code easier to follow. Keep your code minty fresh!
Related Topics: Scripting, Programming, PHP
Jonathan Snook is a freelance web developer and consultant. When not working on one project or another, this proud father can be found spending time with his son and wife in beautiful Ottawa, Ontario, Canada.