I understand the following function because variable hoisting happens. foo();
function foo() {
console.log( a ); // undefined
var a = 2;
}
However what I don't understand is the following part. I got Reference Error, why?
foo()
function foo() {
console.log( a ); // Reference Error
a = 2;
}
--- Edit ---
So far, what I understand from the answers is the second does not make any hoisting and we cannot use any undefined variable.
foo()
function foo() {
// we cannot use any undefined variable, which "a" here
console.log( a );
window.a = 2;
}
For example
var a;
a; //undefined
b; //Reference error