Page 1 of 2
As the second alert is before the declaration of j the result is that it displays "undefined".
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.
You start off with a nice easy function which does something or other and makes use of a global variable called 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:
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 :
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.