
All variables declared in a function are defined throughout the function
var scope = "global";
function f( ) {
alert(scope); // Displays "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined everywhere
alert(scope); // Displays "local"
}
f( );
So previous function equal the following one:
function f( ) {
var scope; // Local variable is declared at the start of the function
alert(scope); // It exists here, but still has "undefined" value
scope = "local"; // Now we initialize it and give it a value
alert(scope); // And here it has a value
}
This example illustrates why it is good programming practice to place all your variable declarations together at the start of any function.

Comments
CodeGuru on on 3.03.2009 at 11:40 AM
Nice hint, didn't know about before.