I am reading Douglas Crockford\'s book \"Javascript: The Good Parts\". He is talking about scope and saying that JS doesn\'t have block scope:
In many mod
Declare variables at the top of the function as a means of documenting all variables used in one place.
It also avoids confusion resulting from someone imagining that a variable is block-scoped when it is in fact not, as in the following:
var i=0;
if (true) {
var i=1;
}
// what is i? C programmer might imagine it's 0.
If variables are also being initialized at declaration time, putting the declarations at the top avoids potential problems with the timing of the initialization:
console.log(foo);
var foo = 1;
In this case, foo is hoisted so it is declared at the time of the console.log, but has not yet been initialized. So this is effectively like
var foo;
console.log(foo); // no ReferenceError, but undefined
foo = 1;