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 modern languages, it is recommended that variables be declared as late as possible, at the first point of use. That turns out to be bad advice for Javascript because it lacks block scope. So instead, it is best to declare all of the variables used in a function at the top of the function body.
However, I couldn't think of a good example why this statement makes sense and it would be really nice to see some examples which verify this statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With