Slightly confused by this Eloquent Javascript explanation of parameters and scopes.
It states that variables declared outside of a function are global, that variables declared inside a function are local, and that variables declared inside a function without a preceding var
are essentially referencing a similarly named global variable. Fine. That makes sense. But then this code throws me for a loop.
var x = "outside";
var f1 = function() {
var x = "inside f1";
};
f1();
console.log(x);
// → outside
var f2 = function() {
x = "inside f2";
};
f2();
console.log(x);
// → inside f2
Logging out the value of x in the first function should result in "inside f1" because that variable was declared locally. And that second function (being that it contains a variable declared without var
and thus references the global one declared up at the very top) should result in "outside." But...it doesn't in either case.
I get the gist of what's supposed to happen. But unless I'm reading incorrectly, it seems as if it's the opposite of what the author describes. This can't be a typo.