I'm trying to figure out how this works. When I reference a named Javascript function that hasn't been declared yet, in some circumstances, it works. But if I use a function literal, it doesn't, but it also doesn't fail with a ReferenceError
.
function works() {
var works_ref = foo;
function foo() {
console.log('ok');
};
console.log('works ' + works_ref);
}
function fails() {
var fails_ref = foo;
var foo = function() {
console.log('ok');
};
console.log('fails ' + fails_ref);
}
works();
fails();
This returns
"works function foo() {
console.log('ok');
}"
"fails undefined"
I'm wondering how the first example works—this is an interpreted language, not compiled, so I'd expect any sort of forward reference to fail—and why doesn't the second example generate a ReferenceError
?