1

I am learning about Persistent Lexical Scope References when it comes to function memory in JS. It caused me to reflect on what the parentheses are actually doing when it comes to function calls.

If I store a function inside a variable, that variable contains/has access to a function definition and return value, correct?

So, when the JS engine sees () after a function label, it knows to call the functionality associated with that label and executes accordingly producing a return value.

Please let me know if I am missing anything with this logic. Thanks!

function myFunc() {
    let x = 0;
    function inner() {
       x++;
    };
    return inner;
}

let another1 = myFunc();     // stores the functionality of inner();

another1();                  // JS engine runs inner() which increments and stores the value of x to be used again;
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
chiahao
  • 21
  • 1
  • This phenomenon is called [**closure**](https://stackoverflow.com/q/111102/9867451). JS engine runs `inner` but that call doesn't store `x`, `x` is already stored (trapped in the closure created by `inner`). – ibrahim mahrir Jun 17 '20 at 23:58
  • Also, in javascript everything is either a primitive value or an object. Functions are objects, so when assigned around to variables, they are not duplicated, just their reference (a pointer of sorts) is assigned. More on that [**here**](https://stackoverflow.com/q/37290747/9867451) – ibrahim mahrir Jun 18 '20 at 00:00

0 Answers0