1) The reason this alerts 1
is because even though you are invoking the test()
function beforehand, it itself is invoking and creating its own closure and declaring a separate var example = 2;
inside of it. (So your alert can't see it, it only sees 1). Now if you did: return example = 2;
you would notice alert(example) === 2. This is because you brought the example out from the closure and it effected the previous example variable.
example = 1;
function test(){
var example = 2;
}
test();
alert(example);
2) Here, you aren't creating a new variable inside of the function, so it is able to access (through closure) the variable example outside of it, and change it to 2.
example = 1;
function test(){
example = 2;
}
test();
alert(example); //alert 2 no matter if example=1 or var example=1 before function
3) This last one is a good example of how 'closure' works here. Variables, unlike let's say the function ()
must be declared above something that tries to access them. Functions on the other hand don't. So although var example = 1
might be below the function test() { }
itself, it doesn't matter. What's important is that it is declared before the CALL to test()
. This is when the closure is created and it wraps itself around any variables etc it can see/access.
// so this ...
var example = 1;
function test(){
alert(example);
}
// and this work ...
function test(){
alert(example);
}
var example = 1; // <-- notice it's still above the test() func call, it can still see example
test(); //always alert 1, no matter if var example=1 or example=1 before function
// if var example = 1; was down here below it, it would alert "undefined", this is because
// the variable was not available within the scope when test() was called.