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?
This is called function declaration. This will be processed at the compile time. So, JavaScript knows that there is a function called
foo. That is why it assigns the function object hereIn the second case,
foois a variable, which is declared later in the function. So, because of hoisting,is aware of the fact that
foois defined somewhere in the function but it doesn't know the actual value of it. Because the value assignmentvar foo = function() {}happens at the runtime. That is why the default valueundefinedis used forfootill the actual assignment statement is executed.