I am trying to understand how this works. When I reference a named Javascript function that is not yet declared, it works in some cases. But if I use a function literal, it is not, but it also does not interrupt with 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();
It returns
"works function foo() {
console.log('ok');
}"
"fails undefined"
I am wondering how the first example works: it is an interpreted language, not compiled, so I would expect some direct link to fail & mdash and why does the second example not generate ReferenceError?
source
share