I\'ve been learning Javascript using Object-Oriented JavaScript by Stoyan Stefanov
He offers an example comparing global and local scope:
var a = 123
In simple words, all the declarations, of both variables and functions are considered first. So local var a
in effect will override global variable only in local scope and will have no value i.e. undefined
. So first alert will show undefined
. Second alert will show 1 as it is after a = 1
. This just happens locally and global variable a will have value 123 - it won't be changed.
another example using function to show how it works
function show(){
alert("I am global");
}
function f() {
show();
show = function(){
alert("I am second");
}
show();
function show(){
alert("I am first");
}
}
f();
show();
It is not overriding the global variable. What is happening is called "variable hoisting". That is, a var a;
gets inserted at the top of the function.
The script engine changes your script to be the following:
var a = 123;
function f() {
var a;
alert(a);
a = 1;
alert(a);
}
f();
Lesson to learn: Always declare your variables before you use them. Some will say declare all your variables at the top of the function.