That happens because of hoisting, which is putting all var
statements at the top of the function, but still executes the assignment statement at the line it was made. If you have a look below, the second var variable
will shadow the global variable since it declares a local variable with the same name. Then, this newly declared variable will be undefined
until it reaches the assignment line.
Basically, here's what your code does:
var variable = "top-level";
function parentFunction() {
var variable;
function childFunction() {
alert(variable);
}
childFunction();
variable = 'local';
}
parentFunction();