The first example is quite straight-forward: You declare an a
variable which your b
function closes over. So b
sets a
to 10
.
Your second example is deliberately complex and confusing. You declare an a
variable that b
closes over, but then shadow it with an a
variable inside b
. To make matters worse, there's also a function declaration of a
that is also in scope in b
. The var
wins over the function declaration, because function declarations are processed before var
statements are. The outer a
is completely unaffected by b
, so the console.log
at the end logs 1.
That's easier to describe with a diagram of sorts:
var a = 1; // <== The declaration `b` closes over
function b() {
var a = 10; // <== The inner `a` variable
return; // <== Returns from `b`
function a() {} // <=== Declaration that was processed immediately
// upon entering `b` (the `return` doesn't affect it
// at all), but which is then superceded by `var a`
}
b();
console.log(a); // Logs 1