I've read that a good practice is to put a var statement which defines all local variables at the top of each function. The following code shows why this is a good idea, since apparently a var after a variable is used makes it undefined.
But can someone tell me why this is the case?
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var a=1;
function foo() {
//a = 2; //outputs 2,2 because this overwrites the external variable value
//var a = 2; //outputs 2,1 because the "var" keyword creates a second variable with local scope which doesn't affect the external variable
console.log(a);
var a = 3; //ouputs "undefined,1" ???
}
foo();
console.log(a);
};
</script>
</head>
<body>
</body>
</html>