Noob
Noob

Reputation: 2807

Function returning function and no reference

My question is about this function:

    function d() {
       function e() {
        alert('E');
       }
       return e;
    }
    d()();//alerts 'E'

When function d is called first time function e is returned, however, nothing holds reference to the returned value( function e in this case), and this returned value should be lost. So, how does this d()() work ? It's not a closure according to my understanding. Thank you !

Upvotes: 3

Views: 259

Answers (3)

zfrisch
zfrisch

Reputation: 8670

function d() {
   function e() {
    alert('E');
   }
   return e;
}
d()();
//alerts 'E'

It doesn't need a reference because it is explicitly transformed into the returned value. Unless stored, the result of a JavaScript Expression( a sequence of interpreted variables, functions, and/or operations that returns a value ) will be fully evaluated and then removed from memory. The key is that it has to be fully evaluated. You can almost think of functional execution as horizontal Russian Nesting Dolls. The JavaScript expression is:

d()();

So it begins left-to-right with:

d()

which is executed and returns:

function e() { ... }

which turns the line into:

function e() { ... }()

which is then executed, alerts, and returns:

//nothing

The full Expression is completed. There is nothing left for it to do. The reference isn't stored anywhere and immediately after this expression is resolved everything that was returned from its evaluations is thrown away.

Upvotes: 1

Pointy
Pointy

Reputation: 413916

The call to d (which is d() in that last line) returns e, and then the last () immediately calls that function.

Consider

function n() { return 5; }

console.log(n() + 1); // 6

Nothing holds the return value from the call to n(), and yet the return value can be used in the addition operation. The return value from the call to d() can similarly be used as a reference to a function in a function call expression, which is exactly what happens in your code.

To put it another way, d() returns a reference to a function (e). In order to call a function, all you need is a reference to a function taken from somewhere, and a parenthesized argument list. That's what d()() gives you.

Upvotes: 4

ziggy wiggy
ziggy wiggy

Reputation: 1067

You don't need a named reference to a function in order to use it. You can apply an operator to the result of any expression in place, and the () function call is just another operator.

So it's little different from performing addition on the result of a function call.

function returnTwo() {
  return 2;
}

console.log(returnTwo() + 40);

Here we don't store the result of returnTwo(), but we can still use it as the left operand of the + operator. So with the function call in your example, you're doing the same thing.

Upvotes: 1

Related Questions