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 = 10;
return;
function a() {}
}
b();
alert(a);
Using the code above, the browser will alert “1”.
I’m still unsure why it returns “1”. Some of the things he says come to mind like:
All the function declarations are hoisted to the top. You can scope a variable using function. Still doesn’t click for me.
Function hoisting means that functions are moved to the top of their scope. That is,
will be rewritten by the interpeter to this
Weird, eh?
Also, in this instance,
behaved the same as
So, in essence, this is what the code is doing: