0

Assume that, I have following a codes in document.ready event

$(function(){
      var a=1;
      $("#btn").on("click",function(){
          a++;
          var b=1;
          function foo(){
               alert(a*b);
               b++;
          }
     }
 }

In this case, what is the life time of variable 'a' and 'b'. Is new 'b' allocated in every call of click event and previous b deleted by garbage collector?

overlord
  • 489
  • 1
  • 7
  • 20
  • Possible duplicate of [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – andrew Feb 11 '16 at 19:25
  • 1
    The lifetime of `a` is the same as of the `click` callback and depends on how long it is attached to the DOMElement. About `b` if there would have been a Object assigned then yes the Object assigned to `b` would be gc if it was not referenced anywhere anymore (not the variabel is gc but the object that was assigned to it) – t.niese Feb 11 '16 at 19:28
  • If you would be using `let` instead of `var` it should be a new b every time. – Jannis Lehmann Feb 11 '16 at 19:28
  • @Cludch no in this particular example there would not be a difference in using `let` and `var` – t.niese Feb 11 '16 at 19:29
  • Oh, yeah you're right. But when using `var` it would be still the same variable, wouldn't it? – Jannis Lehmann Feb 11 '16 at 19:31
  • @Cludch no look at this [example](https://jsfiddle.net/xfuya56e/1/) both `res1();` and `res1();` will do `console.log(b);` but both `b` are different variables. `res1` will log `value1` and `res2` will log `value2`. – t.niese Feb 11 '16 at 19:35
  • @overlord `b` will already be gone at the end of the execution of the callback function and not at the the next click.. – t.niese Feb 11 '16 at 19:42
  • Thanks for your reply. I have one more question: What about 'foo' function? Can we same things like b. Is it allocated in every button click?I am very new at java script and I haven't experience like this situation in other language that I use. – overlord Feb 11 '16 at 20:18

0 Answers0