Why is the alert not displayed if we run the extFunc () function?

function extFunc() { var a = 123; return function intFunc() { alert(a); } } extFunc() // ---- 

But alert is displayed if we assign a function to a variable and run through this variable? What possibilities does the assignment of a variable function open here? Thank!

 var newFunc = extFunc(); newFunc(); // 123 
  • No new features ... Try extFunc()(); The variable itself is not in the business here. - vp_arth

1 answer 1

In the original version, extFunc returns a function, but does not call it. In the second variant, you put the function that extFunc returned to the variable newFunc and then call it. The first option will work in this form.

 function extFunc() { var a = 123; return function intFunc() { alert(a); } } extFunc()() 

  • Those. if we assign a function to a variable, then a call through this variable will automatically run all nested functions? - Ivan Testovich
  • Not. See it. extFunc returns a function and you place this returned function in newFunc. And when you use the newFunc () construct, it is not a nested function that is called, but a function that is in the variable newFunc - tilin
  • I don’t understand why then newFunc () calls the nested function without add. call newFunc () (); Those. newFunc () gets control over all functions embedded in it at once and starts them right away? - Ivan Testovich
  • It does not call a nested function. newFunc () is a call to a function that lies in the variable newFunc. And there lies what extFunc returned after calling extFunc (). newFunc () () can be viewed from left to right: first, newFunc is called, which returns a function, and then this function is called as follows () - tilin
  • It is clear, but not until the end) Thank you! Tell me, please, what topic should I read it in order to finally enter? Closures? - Ivan Testovich