2

Just out of curiosity, if I was to set a variable in JavaScript like this:

var name = "Mango";

Then never reference it would JavaScript "automatically" release the variable from memory if it found that it had never been used, or would this have been ignored all together and nothing would have happened?

Thank you in advance.

  • That depends on how intelligent the runtime is. Since there's a possibility you may be accessing the variable dynamically (`window[userInput]`), this may be very tricky to figure out, but not impossible. – deceze Jun 12 '16 at 15:25
  • @deceze My apologies if I was not clear, I'm talking about the Google (Chrome) V8 engine. –  Jun 12 '16 at 15:35
  • Same thing. Even if it may or may not be able to do that today, that may change tomorrow... – deceze Jun 12 '16 at 15:50

2 Answers2

1

It would not be deleted, Remember that JavaScript never "looks ahead".
It will never keep track of what will be used in the future.
For all JavaScript knows, you could open a developer's console (assuming this is for a browser) and inject code that does use mango.
In general, JavaScript will only delete things that can never be reached.

For example, if you were to then execute:

name = "Hi";

The string "Mango" would be automatically deleted because there is no reference to it, Source.

  • Yes, this is for a browser also Thank you for the answer & the link, +1. –  Jun 12 '16 at 15:39
1
  • If it's a Local variables, it automatically gets garbage collected once it goes out of scope.
  • If we talk about Global variables, global variables are never disposed of by the GC in the sense that a global variable will still exist. Setting it to NULL will allow the memory that it references to be collected.
Vivek Pratap Singh
  • 9,326
  • 5
  • 21
  • 34
  • 1
    Closures can keep local variables alive even after the function that declared them has returned, can they not? – meriton Jun 12 '16 at 15:42
  • @meriton I think local variable which are captured by closures gc'ed once the function they are defined in has finished and all functions defined inside their scope are themselves gc'ed. – Vivek Pratap Singh Jun 12 '16 at 15:47