0

Just started to learn closures and wrote this code in FireBug:

var later;

function outerFunc() {
  var innerVar = "Inside Outer";
  function innerFunc() {
     console.log(innerVar);
  }

  later = innerFunc;
};

outerFunc();
later();

But on calling later(); it returns an undefined value. Shouldn't it print out "Inside Outer" ?

excentris
  • 471
  • 1
  • 7
  • 25
  • 2
    It does for me: http://jsfiddle.net/sMuNV/ . `console.log` doesn't `return` anything, and your function doesn't `return` anything. Did you really mean to say "return"? – Ian Apr 08 '13 at 18:26
  • 1
    [`Status: no-repro`](http://jsfiddle.net/ccjAB/) – Matt Ball Apr 08 '13 at 18:26
  • 4
    When I run it (in Chrome's web inspector) I do get "Inside Outer" (which, to answer your question, is the correct behavior). The result of that entire expression is `undefined` because there's no return values and the last expression doesn't evaluate to anything. Are you sure "Inner Outer" isn't being printed as well? – jmar777 Apr 08 '13 at 18:26
  • I checked code and it works... http://jsfiddle.net/GKDev/Y3fdV/ – Givi Apr 08 '13 at 18:28
  • 1
    [This](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) SO question has some great answers that may help you in the process of learning how closures work. – excentris Apr 08 '13 at 18:34
  • well I mean shouldn't it print it TWO times? one time when I am calling outerFunc... one time when I am calling later() ? –  Apr 08 '13 at 18:47

1 Answers1

1
var later;

function outerFunc() {
  var innerVar = "Inside Outer";
  function innerFunc() {
     console.log(innerVar);
  }

  later = innerFunc;
};

outerFunc(); //Don't run innerFunc, just set later = innerFunc
later(); // Execute innerFunc

So it logs it just one time.. It seems nice..

fernandosavio
  • 9,849
  • 4
  • 24
  • 34
  • well I mean shouldn't it print it TWO times? one time when I am calling outerFunc... one time when I am calling later() ? –  Apr 08 '13 at 18:48
  • 2
    @user1899082 no should not, because when you call **outerFunc();** it's just assign name of **function innerFunc** to **later** and that is all. If you want to call it twice you should, instead of ***later = innerFunc;*** do so ***later = innerFunc();*** – Givi Apr 08 '13 at 18:56