Javascript processes variable declarations before code and it moves all the declarations to top of scope. This behavior is called hoisting. Read here for more information.
It is a generally considered good practice to declare all javascript variables at top of scope.
In understanding of hoisting one fact that is often overlooked is that only declarations are hoisted - not initializations.
var x = 101;
var foo = function() {
x = 102;
console.log(z);
};
var z = x;
foo();
What is the outcome of above code?