1

Can someone explain why the code below fails?
How i can access the zip function using closures? I want it to get it to print out value1.

function foo() {
    var bar;

    function zip() {
        var quux = 'value1';
        bar = true;    
        console.log(quux);
    }

    quux = 'value2';
    console.log(quux);
    return zip;      
}

foo();

var a = zip;

a();

It is currently saying zip is not defined.

Yeldar Kurmangaliyev
  • 30,498
  • 11
  • 53
  • 87
  • 3
    Because `zip` is undefined outside `foo()`. You have to use `var a = foo()` instead. – hindmost Nov 03 '15 at 11:24
  • Hmm it's interesting what are you trying there. You might wanna take a look at [the revealing module pattern](http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript) – memo Nov 03 '15 at 11:26

2 Answers2

5

You can use:

foo()()

or the same with assignment to a variable:

var a = foo();
a();

Note that it will output both value2 and then value1.

How is this working?

In order to make it easier to understand the provided code, consider the following example which makes the same result as your code:

function foo() {
  var bar;
  quux = 'value2';
  console.log(quux);

  return function() {
    var quux = 'value1';
    bar = true;

    console.log(quux);
  };
}

var a = foo(); // executes code, returns function and stores it in a variable
a(); // executes function, stored in a variable

I guess, it is easier to understand this code now - it executes some code, returns a function, which you call later.

Now, consider another example:

function foo() {
  var bar;
  quux = 'value2';
  console.log(quux);

  var zip = function() {
    var quux = 'value1';
    bar = true;

    console.log(quux);
  };

  return zip;
}

var a = foo(); // executes code, returns function and stores it in a variable
a(); // executes function, stored in a variable     

This code does the same, but it stores a function in a variable before returning as result. The code that you have provided in example almost does not differ from the last example, except for function declaration:

These are almost equivalent (why almost?):

var zip = function() {
};

function zip() {
}
Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 30,498
  • 11
  • 53
  • 87
0

The function 'foo' is returning the 'zip' function but not called(ex: zip()). Hence you may have to capture the returning function in a variable.

var f = foo();

Then call:

f();

Output:

value2
value1
SSS
  • 92
  • 4