JS var parsing

2009-11-21

When dealing with Javascript, you often hear that you should put your vars at the top of your function. It's not often you actually get to hear why, though. Let me try to show you. Observe (from Jake Archibald):

Code: (JS)
var msg = "spatchcock";
function doStuff() {
alert(msg);
if (false) {
var msg="spotted dick";
}
}
doStuff();
alert(msg);

What will be alerted the first and second time?

It's very intuitive to think that var declarations are only parsed if the logic actually reaches the declaration. But what happens here is that the var got defined when parsing the function. So even though the condition was never true and even occurs after the initial alert, the alert is still undefined because the inner msg shadows the outer msg.

That's why, for clarity and (at some point) your own sanity, you should always write it like this:

Code: (JS)
function doStuff() {
var msg;
alert(msg);
if (false) {
msg="spotted dick";
}
}

Hope it helps ya!