Do you know what value produce this code in JavaScript?

var foo = 1;
function bar() {
if (! foo) {
var foo = 10;
}
alert(foo);
}
bar();

If you are surprised what will produce "10", then the following code confuse you at all:


var a = 1;
function b () {
a = 10;
return;
function a() {}
}
b();
alert(a);

In this case, the browser produces "1". So what exactly is going on? Although this behavior seems strange, dangerous and confusing, in fact it is very powerful and significant tool JavaScript. There is a name for term for such behavior, which is “hoisting”. This article will try to explain the mechanism of the language, but first let us talk about scope in JavaScript.
Sparks 30 october 2011, 17:14