Variables declared even if unused
Javascript "uses" the variable, even if it's declared in an if statement. Most people probably won't run into this. I only did by accident in trying to get some cross-browser stuff working. Here's an example:
var i=5;
function test(){
var a;
if(a==0){var i=5;}
alert(i);
}
Would you expect it to alert 5? In fact, it alerts as undefined. Even though the code within the if statement never gets executed, it still uses declares the variable. It's as if the following is happening:
var i=5;
function test(){
var a;
var i;
if(a==0){i=5;}
alert(i);
}
In fact, it'd be wise advice that any variables that you plan to use in a function should be declared at the top of the function outside of any control structures to prevent this from happening.
I just noticed one little oddity in all this and that is in how Firefox seems to handle passing in an event object. Here's another example:
var i=5;
function test(i){
var a,i;
if(a==0){i=5;}
alert(i);
}
window.onload = test;
The argument of the test function is the Event object in Firefox. But I redefine the i
variable on the first line. You'd expect i
to be undefined as a result. Instead, the alert actually gives us our event object. It's only when I actually give my variable a value will it overwrite the event. Things to keep in mind!
Conversation
I have to say I had to look this up, but here's the explanation. All quotes from JavaScript the Definitive Guide v4.
That explains your second observation: `var i;` doesn't overwrite anything, it'll only do that if you use `var i = null;`
Now, for your first observation:
The book then shows an example which is about the same as your first observation. It boils down to this:
In your example this means that `i` is declared, and thus overwrites `i` in global scope, but does not yet have a value, because it isn't initialized (since `a != 0`).
P.S. It would be handy if you'd allow the use of <code> in the comments ;-)
P.P.S. The notification checkbox status isn't preserved when you preview your comment.