-1

In the following example, how is y given the value of 1? I added some logging to see values and don't understand how/where y is assigned...

(function() {
    function foo(x) {
        var callNum = 0;
        var baz = 3;
        return function (y) {
            callNum++;
            console.log("callNum: " + callNum);
            console.log("y: " + y);
            console.log("baz: " + baz);
            console.log("x: " + x);
            console.log(x + y + (++baz));
        }
    }
var moo = foo(2); // moo is now a closure.
moo(1);
moo(1);
})();

Here's the fiddle output log:

    callNum: 1   
    y: 1   
    baz: 3
    x: 2 
    7 
    callNum: 2 
    y: 1 
    baz: 4 
    x: 2 
    8 

2 Answers2

2

foo() returns a function. This returned function accepts a single argument, the y you are concerned with.

So when you do this:

// returns a function that accepts `y` with `x` shared via closure
var moo = foo(2);

// execute the inner function, passing in a value for `y`.
moo(1);

foo(2) returns a function. x is now 2. moo is now a function that accepts a value for y, and you pass in 1. So y is now 1.


To think of it another way, you can invoke your inner function by doing:

foo(x)(y);

Or with the values you are using:

foo(2)(1);

So, in answer to your question, y gets set to 1 when you do:

moo(1);
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
0

In your code:

(function() {
    function foo(x) {
        var callNum = 0;
        var baz = 3;

These are the parameters that matter (x, callNum and baz). They form closures involving the following function:

        return function (y) {

This function has a closure to each of the outer local variables (including moo and foo).

            callNum++;
            console.log("callNum: " + callNum);
            console.log("y: " + y);
            console.log("baz: " + baz);
            console.log("x: " + x);
            console.log(x + y + (++baz));
        }
    }

There are also closures involving moo and both the above functions, however it's not used so is irrelevant to the outcome.

var moo = foo(2); // moo is now a closure.

The rest is answered by Alex.

RobG
  • 142,382
  • 31
  • 172
  • 209