Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a nested anonymous function (javascript)

Tags:

javascript

I"m new to Javascript and programming in general and came upon this block of code from a book called Javascript Enlightenment (p.88):

var parentFunction = function() {
    var foo = 'foo';
    return function() { // anonymous function being returned
        console.log(foo); // logs 'foo'
    }
}
// nestedFunction refers to the nested function returned from parentFunction

var nestedFunction = parentFunction();

nestedFunction(); /* logs foo because the returned function accesses foo
via the scope chain */

Why does setting var nestedFunction = parentFunction(); enable nestedFunction(); to invoke the nested anonymous function and log "foo" to the console whereas using just parentFunction(); logs nothing at all?

like image 505
edubba Avatar asked Oct 16 '25 01:10

edubba


1 Answers

Invoking parentFunction returns the anonymous function without calling it.

nestedFunction gets set as the return of parentFunction, the anonymous function.

Invoking nestedFunction hence invokes the anonymous function.

The anonymous function uses console.log so you see "foo".

like image 88
Paul S. Avatar answered Oct 18 '25 13:10

Paul S.