Explain in detail about Reference-counting garbage collection in JavaScript?

 Reference-counting garbage collection

This is the simplest garbage collection algorithm.This algorithm looks out for those objects which have no references   left.An object becomes eligible for garbage collection if it has no references attached to it.The garbage collection is   explained in the below example.


var obj = {
      x: { y: 2 }
         // 2 objects created. One is referenced by the other as one of its properties.
         // Obviously, none can be garbage-collected
obj = 1; // what was the 'x' property of the object originally in obj
         // has zero references to it. It can be garbage collected.


When it comes to cycles there are limitations in Reference-counting garbage collection and it is explained in the below example.


In the following example,two objects were created and referenced one another there by creating a cycle. After a function call they will go out of scope, so they are effectively useless and could be freed.But the reference-counting algorithm considers that since each of the two objects is referenced at least once, neither can be garbage-collected.

function f() {
var obj1 = {};
var obj2 = {};
obj1.p = obj2; // o1 references o2
obj2.p = obj1; // o2 references o1. This creates a cycle.