The scope of a variable declared with var
is the entire function in which it is declared, it doesn't start at the point of declaration. It's often described as variable declaration hoisting and can be seen as a move of all variable declarations to the start of the function. For function definitions, both the declaration and the "assignement" are moved together.
function b() {
a = 10;
function a() {}
}
is equivalent to
function b() {
var a = function() {};
a = 10;
}
which means you declare a new variable a
, and the a = 10
statement only changes the internal variable a
, not the external one. We say the internal variable a
shadows the external one.
In the second case, there's no variable a
in the internal scope, which means the external one is used and changed (when looking for a variable, you go from the internal scope to the most external one following the closure chain).