|The Undefined Defined Variable|
Page 2 of 2
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.
Notice that hoisting only moves the declaration of the variable and not any initialisation. With hoisting taken into acount our function reads more like:
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.
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.