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
Declaring variables at the top helps you avoid situations like this:
function outer() {
var i = 50;
function inner() {
alert(i);
var i= 30;
}
inner();
}
outer();
Many people would expect the alert to show 50
, and they would be surprised to see undefined
. That's because the i
variable is declared within the inner
function, but it isn't initialized until after the alert
. So it has full function scope, even though it's declared after its initial use.