I just read a great article about JavaScript Scoping and Hoisting by Ben Cherry in which he gives the following example:
var a = 1;
function b() {
a =
Hoisting is a concept made for us to make it easier to understand. What actually happens is the declarations are done first with respect to their scopes and the assignments will happen after that(not at the same time).
When the declarations happen, var a
, then function b
and inside that b
scope, function a
is declared.
This function a will shadow the variable a coming from the global scope.
After the declarations are done, the values assign will start, the global a
will get the value 1
and the a inside function b
will get 10
.
when you do alert(a)
, it will call the actual global scope variable.
This little change to the code will make it more clear
var a = 1;
function b() {
a = 10;
return a;
function a() { }
}
alert(b());
alert(a);