The Undefined Defined Variable
Article Index
The Undefined Defined Variable
Solution

Solution

The answer to the problem is "hoisting".

When you declare a variable within a function the declaration is automatically moved to the start of the function - i.e. it is hoisted to the top.

You can write Javascript for years without ever running into problems with hoisting or even being aware that it is going on - but when you blunder into it as in our example it can seem very strange.

Notice that hoisting only moves the declaration of the variable and not any initialisation. With hoisting taken into acount our function reads more like:

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

Now it is perfectly clear why i is undefined.

The local variable i has been declared at the start of the function as the result of hoisting so hiding the global variable i which isn't initialised until the for loop starts.

Now it is perfectly obvious why i is reported as undefined.

Notice that the declaring of the variable in the for loop is quite irrelevant to the the problem which would have happened no matter how i was declared. This is all a matter of where i is declared not how.


Banner

Pattern

The pattern that you need to follow to make sure that hoisting never causes you any problem is simple:

always declare, and if appropriate initialize, all of the variables that a function uses at the start of the function.

Following this pattern makes hoisting explicit.

 

 

Banner

More Puzzles

C++
A problem of order - constructor initialization

Initializers can be used to make constructors more elegant but they also introduce subtle problems. This brainteaser for C++ programmers illustrates a common pitfall.


Sharpen Your Coding Skills
Jigsaw Puzzles and The MacMahon Squares

Another puzzle featuring Joe Celko's characterful pair, Melvin Frammis, an experienced developer at International Storm Door & Software, and his junior programmer sidekick, Bugsy Cottman. This cla [ ... ]


Javascript
JavaScript Puzzle - The Too Tidy Assignment

There is a rule about not optimizing code too soon. Perhaps we should add to that the rule that being too tidy is often a mistake. Here we have a JavaScript example where things go wrong because of an [ ... ]


Other Articles

<ASIN:059680279X>

<ASIN:0470526912>

<ASIN:1590597273>

<ASIN:0596806752>



 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.