Javascript named functions are available before declaration, but function literals are not

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?

+4
source share
2 answers
function foo() {
    console.log('ok');
};

. . , JavaScript , foo.

var works_ref = foo;

var foo = function() {
    console.log('ok');
};

foo - , . , - hoisting,

var fails_ref = foo;

, foo - , . var foo = function() {} . undefined foo , .

+5

- , :

function works() {
    var works_ref = undefined;

    function foo() {
        console.log('ok');
    };

    works_ref = foo;

    console.log('works ' + works_ref);
}

function fails() {
    var fails_ref = undefined, 
        foo = undefined;

    fails_ref = foo; // <---------- note this line.

    foo = function() {
        console.log('ok');
    };

    console.log('fails ' + fails_ref);
}
+2

All Articles