1

In below code(Node.js), it prints 1 2

   function count(){
        var counter = 0
        function inc(){
            counter++
            console.log(counter);
        }

        return inc
    }
    var x = count();
    x()
    x()

Does that means that variable counter being available to inc() due to closure will live lifetime of the program?

Rhythm Walia
  • 161
  • 2
  • 9
  • Possible duplicate of [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Andrew Li Sep 11 '16 at 05:26
  • In short, yes it will be. It'll be available as long as x is available. – Mike S. Sep 11 '16 at 05:30
  • @MikeS. Thanks, may be you could write this as an answer so that I could accept. – Rhythm Walia Sep 11 '16 at 05:37
  • @AndrewL. I wouldn't say it to be a duplicate per say because the question and answer both don' t highlight the life of a variable shared by closures. – Rhythm Walia Sep 11 '16 at 05:37

1 Answers1

0

Yes it will be. It'll be available as long as x is available.

Mike S.
  • 969
  • 5
  • 13
  • 1
    Well, the question was "will live lifetime of program". The correct answer is actually "No, it'll be available as long as `x` is available`, which is a different thing. –  Sep 11 '16 at 06:36