It is called variable hoisting
. In JS declared variables are actually hoisted (moved up) to top of the scope they bound to, so in your case they are moved up to beginning of your function. In the second example a
is treated as it is actually declared at the top of method before any of the assignments, then assigned to 10
later. So when you print a
the variable is defined but its value is not assigned yet.
var change8 = function()
{
var a;
console.log(a);
console.log("End of function");
a = 10;
}
But in the first example a is not defined with var
keyword so a
will be treated as a global variable and won't be available until the assignment. Thus when it is called before the assignment the error will occur.
For understanding declaring variables with var
keyword check the following answer