0

E.g.

 function log(x) { console.log(x); }
 var preDefinedFunc = () => log(2);
 
 preDefinedFunc();

This will print '2' when run.

How is the predefined function stored? Is it a js object with a reference to log() and another entry for the parameters? Something like:

{ func: ..., params: { ... }}
Will Cowan
  • 81
  • 8
  • 1
    MDN has a [good article](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) on __closures__ and __lexical scope__. You can search more using these 2 keywords. – HosseinAgha Jul 13 '20 at 06:17
  • Functions are (callable) objects in JS, and a reference to that function is stored in the variable (`preDefinedFunc`). Then you've just hardcoded a function call inside the body of the function, that shouldn't be any mindblowing, you did a similar call on the last line too. – Teemu Jul 13 '20 at 06:21
  • It is stored as a function object. The way how it is stored is implementation dependent, but you can think of it's stored as a string (it actually isn't, but that way it's easier to understand), like `"log(2);"` and it is evaluated every time the function is called, using the scope in which it was defined. – FZs Jul 13 '20 at 06:22
  • Also note that `predefinedFunc` doesn't hold a reference to `log`: `var log = function (x) { console.log(x); }; var preDefinedFunc = () => log(2); log = null; preDefinedFunc();` will throw an error saying `null` isn't callable. – FZs Jul 13 '20 at 06:25
  • Maybe it's the [variable scope of JS](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) causing troubles here ..? – Teemu Jul 13 '20 at 06:27

0 Answers0