-1

The question asks in all, Will my variables set by another passed or dynamic variable be reset if untouched for X amount of time?

I looked over ECMAScript specification and I'm still a little confused as to what and when things gets garbage collected. I looked at Lifetime of JavaScript variables and its answer say

"if an identifier is reachable (through a direct pointer or a closure), it shouldn't be Garbage Collected."

So am I gettin this right?

Basically garbage collection happens if variables are set by another passed value.

What about in a ternary operator?

I alternate between two different functions to run 3 every month using a ternary operator as a switch will it know it did condition 1 3 months prior and do condition 2 or am I at risk of garbage collection and it will run condition 1 every time?

Community
  • 1
  • 1
garrettmac
  • 8,417
  • 3
  • 41
  • 60

1 Answers1

1

Variable values are garbage collected at or after such time as there are no more references to the variable.

Recalling that arrays and objects in Javacript are passed by reference, so if

var a={}, b=a;

The object pointed to by a has two references: a and b.

a=null;

Causes the object to have only one reference b, so it is not a candidate for garbage collection.

b=null;

Now the object has no references, so it becomes a candidate for collection.

In terms of closures, the same applies to:

b=function(){
  var a={};
  return a;
};

Where b is a reference to the "closed over" object once referred to by a.

Once the function completed, a went out of scope and was then no longer a reference to the object.

While b is in scope, the object will not be garbage collected until

b=null;

Which frees the object for collection.

When reference-less values are garbage collected is up to the JavaScript engine and typically out of your direct control.

There are ways to trigger an explicit collection but in most cases are rarely needed.

Rob Raisch
  • 17,040
  • 4
  • 48
  • 58