Javascript Scoping Variables Theory
Solution 1:
var
and function
declarations are hoisted before any code is executed.
function letsSee() {
alert(first);
var first;
first = 4;
}
behaves like
function letsSee() {
var first = undefined;
alert(first);
first = 4;
}
As an easier to understand example, you can call functions before they are declared:
foo(); // works!
function foo() { ... }
This is because the function
declaration is looked at first and hoisted, you can call it anywhere regardless of when/where in the code you declare it. The same happens with variables declared using var
. The variable itself (the name) is hoisted. Writing var foo;
anywhere within a given scope will make any higher-scoped variable foo
unaccessible within that scope.
var foo = 'foo';
function () {
alert(foo); // All of these can't see the higher-scoped
doSomething(foo); // foo = 'foo' variable, because the
return foo; // local foo has already been hoisted.
var foo; // masks the higher-scoped foo within the entire scope,
// even if it doesn't appear to be executed
}
Solution 2:
There are two things that are throwing you off
1. your assumption that the <script>...</script>
block has its own scope like a function has scope. The truth is that all <script>
blocks exist in the same global scope.
2. you've also assumed that the var
declaration occurs in the order in which it appears in the code. The truth is that all var
s in a given scope are executed at the beginning of that scope. (-edit- just to clarify: the var declaration happens at the beginning of the scope, but any assignment operation remains at its original spot in the code. The value of a variable that has been declared, but not yet had a value assigned is undefined
).
So... in your first example, var z
is actually declaring z
in the global scope, then the call to demofunction()
operates on that global z
, and both alerts run against the same global z
.
Whereas, in your second example, first
is initially set in the global scope, then declared again within the function's local scope. In the function, the alert and the assignment both operate on the local variable. Outside the function the writeln()
s operate on the global variable.
Solution 3:
I think that is because function declarations are hoisted in JavaScript - i.e. that function runs up the top, where that variable you are trying to access is not defined.
Post a Comment for "Javascript Scoping Variables Theory"