The Undefined Defined Variable
Written by Ian Elliot   
Article Index
The Undefined Defined Variable
Solution

Here's a teaser that poses a practical problem - one that's happened in everyday Javascript programming. See if you can work out the answer before looking at its solution and the pattern to follow to avoid it. 

Banner

Background

Javascript executes code in the order that it is encountered and this includes variable declarations. For example, if you declare and initialise two variables and try to use one before the declaration you will discover that you can't:

var i=20
alert(i);
alert(j);
var j=10;

As the second alert is before the declaration of j the result is that it displays "undefined".

Variables are created when their declarations are encountered by the Javascript engine.

The second fact you need is that if you declare a variable within a function, i.e. if you declare a local variable, it will hide any global variable of the same name.

Banner

Puzzle

You start off with a nice easy function which does something or other and makes use of a global variable called i:

function test()
{
alert(i);
}

Where the alert is supposed to represent some complicated processing involving the variable i.

If you call the function after declaring and initialising the global variable:

var i=20
test();

then everything works as you would expect and the alert displays the value 20 i.e the value of the global variable i.

Next you start to work on the function and develop it. At some point you add and use a local variable i. This is fine because once you define a local variable with the same name as a global variable the local variable hides the global.

So for example the following version should work perfectly :

var i=20
test();
function test()
{
alert(i);
for(var i=0;i<10;i++)
{
alert(i);     
}
}

The new local variable i hides the global variable i after its declaration within the for loop.

However when you run the program the alert now displays "undefined"!

After this the for loop runs perfectly and displays 0 to 9 so clearly the local variable i is working as you would expect.

The fact that at the start of the function i is undefined makes no sense because the variable i is more than defined it is defined twice! Once as  global variable and once as a local variable. At the point the function starts the global variable is most definitely defined and not hidden by the local variable - so what is going on?

Turn to the next page when you are ready to find out.

javascriptpuz

<ASIN:1871962579>

<ASIN:1871962420>

<ASIN:0596517742>