I tried following code:
var a = 5;
function x() {
console.log(a);
}
x();
It runs as expected and prints 5.
But i changed the code so the global variable a will be overwrite as follows:
var a = 5;
function x() {
console.log(a);
var a = 1;
}
x();
It prints undefined. It doesn't make sense for me since the overwrite should be happened right after console.log(a). So what is the problem?
you need to initalize variable a before console.log();
This is happening because your second
a
variable is being 'hoisted' to the top of the function and it hides the firsta
. What is actually happening is this:Here is an article on hoisting from adequately good for further reading on the subject.