… it has function scope. Okay, I get that, but apparently I hadn’t totally wrapped my head around just what that means. In essence, it means that all variables that have a declaration in the function, are declared, regardless of whether or not the line of code which declares them would be executed. Given the following code:
var foo = "bar";
function test() {
console.debug("foo is (1st time)" + foo);
if (false) {
var foo = "baz";
}
console.debug("foo is (2nd time)" + foo);
}
Your console will show something like this:
foo is (1st time) undefined foo is (2nd time) undefined
Which is a little weird since the local declaration of foo was never executed. A quick search didn’t turn up any promising hits, but I imagine that there must be a preprocessing step that executes all variable declarations before the function is run. The very similar function below (diffs in bold):
var foo = "bar";
function test() {
console.debug("foo is (1st time)" + foo);
if ("undefined" == typeof(foo)) {
var foo = "baz";
}
console.debug("foo is (2nd time)" + foo);
}
Yields:
foo is (1st time) undefined foo is (2nd time) baz
A more intentional use is probably (diffs also in bold):
var foo = "bar";
function test() {
console.debug("foo is (1st time)" + foo);
if ("undefined" == typeof(foo)) {
foo = "baz";
}
console.debug("foo is (2nd time)" + foo);
}
Which has output:
foo is (1st time) bar foo is (2nd time) bar
So this isn’t anything groundbreaking, or even weird. It’s clearly defined1, and discussed2, but the consequences eluded me for about an hour last night. Hopefully by writing this article, I’ll remember for next time.