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?