Named functions in Javascript accessible before declaration, but function literals aren't -


this question has answer here:

i'm trying figure out how works. when reference named javascript function hasn't been declared yet, in circumstances, works. if use function literal, doesn't, doesn't fail 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 first example works—this interpreted language, not compiled, i'd expect sort of forward reference fail—and why doesn't second example generate referenceerror?

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

this called function declaration. processed @ compile time. so, javascript knows there function called foo. why assigns function object here

var works_ref = foo; 

in second case,

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

foo variable, declared later in function. so, because of hoisting,

var fails_ref = foo; 

is aware of fact foo defined somewhere in function doesn't know actual value of it. because value assignment var foo = function() {} happens @ runtime. why default value undefined used foo till actual assignment statement executed.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -